2011-06-02 34 views
4

鉴于以下类:Lambda表达式类型推断在继承链中是不同的。为什么?

public class Class1<TObject> { 
    protected void MethodA<TType>(Expression<Func<TObject, TType>> property, ref TType store, TType value) { 
    } 
} 

public class Class2<TObject> : Class1<Class2<TObject>>{ 
    private int _propertyInt; 
    public int PropertyInt { 
     get { return _propertyInt; } 
     set { MethodA(c2 => c2.PropertyInt, ref _propertyInt, value); } 
    } 
} 

public class Class3 : Class2<Class3> { 
    private float _propertyFloat; 
    public float PropertyFloat { 
     get { return _propertyFloat; } 
     set { MethodA(c3 => c3.PropertyFloat, ref _propertyFloat, value); } 
    } 
} 

对于等级2的C#编译器推断通用类型中的“PropertyInt”属性setter lambda表达式基类的,但对于Class3的编译器推断的基类,不只是基类的泛型类型。为什么是这样?代码示例中推断类型的标准是什么。谢谢。

回答

4

首先,TObject泛型参数在Class1中定义。 TObject在Class1中用作MethodA中的类型参数。

在Class2中,传递给基类(Class1)的TObject是一个Class2,所以lambda可以推断出本地属性_propertyInt。

在Class3中,传递给基础的TObject是一个Class2,而不是Class3。因此,lambda的参数被推断,但它被推断为Class2,而不是Class3。

Class2 有一个名为TObject的类型参数的事实是完全巧合的 - 我认为您期望传递给该TObject的任何内容都将被传递到Class1,事实并非如此。

如果定义Class3的如下,它的工作:

public class Class3 : Class1<Class3> { ... } 

鉴于评论,然后我可能提供这种扩展方法基础的解决方案,(假设类型参数只为使这一目的工作):

public class Class1 
{ 
} 

public static class StaticClass1 
{ 
    public static void MethodA<TZen, TType>(this TZen zen, Expression<Func<TZen, TType>> property, ref TType store, TType value) where TZen : Class1 
    { 
     // Do whatever here... 
    } 
} 

public class Class2 : Class1 
{ 
    private int _propertyInt; 
    public int PropertyInt 
    { 
     get { return _propertyInt; } 
     set { this.MethodA(c2 => c2.PropertyInt, ref _propertyInt, value); } 
    } 
} 

public class Class3 : Class2 
{ 
    private float _propertyFloat; 
    public float PropertyFloat 
    { 
     get { return _propertyFloat; } 
     set { this.MethodA(c3 => c3.PropertyFloat, ref _propertyFloat, value); } 
    } 
} 
+0

嗯,你完全正确,Chris,TObject类型(在Class1中)永远是Class2,无论链条多深。现在,我在世界上怎么会想念这个?不幸的是,你的解决方案不适用于我的情况,因为它意味着Class3将不再继承Class2的属性。最简单的解决方案是将C3投射为“Class3”。我的问题是关于我认为推论的不一致,但正如你所指出的那样,它并不矛盾。 – 2011-06-02 02:26:15

+0

请参阅上面的编辑,了解可能有所帮助的备用解决方案。 – 2011-06-02 02:41:13

相关问题