简体   繁体   English

子类相关linq表达式字典

[英]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: 我可以使用LINQ表达式来表达属性,如下所示:

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 . 方差允许您将两个委托的返回类型都视为IEnumerable<Entity> ,但是您不能将两个输入值都视为Entity对象,因为您的方法无法将任何实体转换为指定的输出 The input is contravariant, which wouldn't allow you to unify the type of all of the parameters. 输入是互变的,因此不允许您统一所有参数的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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