我想获取属性的获取(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>
?
答案 0 :(得分:1)
您可以使用Expression.Convert
:
public static Func<Object, Object> CompilePropGetter(PropertyInfo info)
{
ParameterExpression instance = Expression.Parameter(typeof(object));
var propExpr = Expression.Property(Expression.Convert(instance, info.DeclaringType), info);
var castExpr = Expression.Convert(propExpr, typeof(object));
var body = Expression.Lambda<Func<object, object>>(castExpr, instance);
return body.Compile();
}