Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
835 views
in Technique[技术] by (71.8m points)

linq - C# Generic Passing different objects with same properties

I am not sure if what I am doing is possible. I have 2 methods. The body of the 2 methods are exactly identical, however the signature of the method both parameter and return are different. The passed in parameter's properties are changed and the object are different but have the same property name (They are two different Entity Framwork Entities). Inheriting both from a base object is not possible (i think) because these are Entity Framework Entities.

Best to show example then talk about it..

Method 1

private static IQueryable<MapListing> ApplyMapFilterToListings(IQueryable<MapListing> listings, ListingSearchCriteria criteria, bool boolIsPremiumListingsOnly = false)
{
    //setting properties of listings (of type MapListing Entity)
}

Method 2

private static IQueryable<vListing> ApplyFilterToListings(IQueryable<vListing> listings, ListingSearchCriteria criteria, bool boolIsPremiumListingsOnly = false)
{
    //setting properties of listings (of type vListing Entity)
}

Generally I would not mind if the body of the function is exactly identical, however in this case a lot of properties are set conditionally and I want to make these methods exactly identical and idiot proof that they go out of sync.

Also reason I am returing IQueryable<> is because I do other stuff to it after returning

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have two options in my opinion.

  1. Implement an interface

    If you create an interface containing all shared properties and methods, you can create one method accepting that interface, or when using generics, all types implementing it. (Yes, it is possible to implement an interface in EF generated classes)

  2. Use dynamic

    The dynamic keyword will give you a lot of freedom. You can pretend if a property or method exists. This is checked at runtime when you pass in the object. You should use dynamic with care, since it can harm your software quality.

The first option is preferred. It is the best solution, but it requires you to have access over the classes. If the classes are in a third party library, dynamic is probably your only solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...