使用表达式获取属性的 Get Acessor [英] Using Expressions to get a Get Acessor of a property
问题描述
我想获取属性的获取访问器 (PropertyInfo
) 并将其编译为 Func
.声明类型仅在运行时已知.
I want to get the Get Acessor of a Property (PropertyInfo
) and compile it to a Func<object,object>
. The declaring type is only known at runtime.
我当前的代码是:
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();
}
不幸的是,我不得不把作为通用参数,因为有时我会得到一个
Type
的属性,比如typeof(T).GetProperties()[0].GetProperties()
,其中第一个 GetProperties()[] 返回一个自定义类型的对象,我必须反映它.
Unfortunately, I have to put <Object,Object>
as generic parameters, because sometimes I will get the properties of a Type
, like typeof(T).GetProperties()[0].GetProperties()
, where the first GetProperties()[] returns a custom-type object, and I have to reflect it.
当我运行上面的代码时,我得到这个错误:
When I run the code above, I get this error:
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
?
So, what can I do to return a Func<Object,Object>
?
推荐答案
您可以使用 Expression.Convert
将强制转换添加到预期类型和返回类型:
You can add casts to the expected type and from the return type using 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();
}
这篇关于使用表达式获取属性的 Get Acessor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!