我想"包装"特定属性的getter函数,该属性是特定类型的一部分.我有一个抽象类,定义如下:
public abstract class MyAbstractClass<T> where T : MyType
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
好吧,假设我有一个类似下面的具体类:
public abstract class MyConcreteClass : MyAbstractClass<MyConcreteType>
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
现在,应该返回getter方法的包装器的helper方法:
private Func<MyAbstractClass<T>, Object> GetPropertyGetter(PropertyInfo property)
{
var instanceType = Expression.Parameter(property.DeclaringType, "i");
// Taking getter's "body".
var getterBody = Expression.Property(instanceType, property);
// Cast to a generic Object.
var body = Expression.TypeAs(getterBody, typeof(Object));
// Build the expression.
var exp = Expression.Lambda<Func<MyAbstractClass<T>, Object>>(body, instanceType);
return exp.Compile();
}
Run Code Online (Sandbox Code Playgroud)
就像预期的那样,我得到以下异常:
"MyConcreteClass"类型的ParameterExpression不能用于"MyAbstractClass <MyConcreteType>"类型的委托参数.
有没有办法"强迫"这种铸造?提前致谢.