简体   繁体   中英

Dictionary of sub-class related linq expressions

Consider the following code example, modelling base and sub-classes:

class Entity
{
}

class Dough : Entity
{
}

class Bread : Entity
{
    IEnumerable<Dough> TypesOfDough { get; set; }
}

class Baker : Entity
{
    IEnumerable<Bread> TypesOfBread { get; set; }
}

I can express the properties using LINQ expressions like so:

Expression<Func<Bread, IEnumerable<Dough>>> BreadDough = bread => bread.TypesOfDough;
Expression<Func<Baker, IEnumerable<Baker>>> BakerBread = baker => baker.TypesOfBread;

So, I have the following expression types:

Expression<Func<Bread, IEnumerable<Dough>>>
Expression<Func<Baker, IEnumerable<Baker>>> 

Is there any way to define a dictionary type which could store both of these expressions, via their base type?

I tried but my guess is, co-variance or contra-variance doesn't allow it.

No, all classes are invariant with respect to their generic type arguments. But even if they weren't, or you were storing delegates instead of expressions, you still couldn't leverage variance. Variance would allow you to treat the return type of both delegates as IEnumerable<Entity> , but you couldn't treat both input values as Entity objects because your methods cannot translate any entity into its specified output . The input is contravariant, which wouldn't allow you to unify the type of all of the parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM