使用表达式获取属性的获取权限
本文关键字:获取 权限 属性 表达式 | 更新日期: 2023-09-27 18:34:00
我想获取属性(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>
?
您可以使用
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();
}