【发布时间】:2013-10-04 15:10:27
【问题描述】:
我想获取属性的获取访问者 (PropertyInfo) 并将其编译为 Func<object,object>。声明类型仅在运行时知道。
我当前的代码是:
public Func<Object, Object> CompilePropGetter(PropertyInfo info)
{
MethodInfo getter = info.GetGetMethod();
ParameterExpression instance = Expression.Parameter(info.DeclaringType, info.DeclaringType.Name);
MethodCallExpression setterCall = Expression.Call(instance, getter);
Expression getvalueExp = Expression.Lambda(setterCall, instance);
Expression<Func<object, object>> GetPropertyValue = (Expression<Func<object, object>>)getvalueExp;
return GetPropertyValue.Compile();
}
不幸的是,我不得不将<Object,Object> 作为泛型参数,因为有时我会得到Type 的属性,比如typeof(T).GetProperties()[0].GetProperties(),其中第一个GetProperties()[] 返回一个自定义类型的对象,并且我必须反映它。
当我运行上面的代码时,我得到了这个错误:
Unable to cast object of type 'System.Linq.Expressions.Expression`1[System.Func`2[**CustomType**,**OtherCustomType**]]' to type 'System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.Object]]'.
那么,我该怎么做才能返回Func<Object,Object>?
【问题讨论】:
标签: c# api reflection lambda expression