使用防爆pressions获得获取财产Acessor [英] Using Expressions to get a Get Acessor of a property

查看:183
本文介绍了使用防爆pressions获得获取财产Acessor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要得到的获取属性的Acessor(的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.

我目前的code是:

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();

}

不幸的是,我必须把&LT;对象,对象&gt; 作为泛型参数,因为有时候我会得到的键入<属性/ code>,如的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.

当我运行上面的code,我获得OS 3.0的错误:

When I run the code above, I getthis 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键&LT;对象,对象&gt;

推荐答案

您可以添加类型转换预期的类型和使用的返回类型防爆pression.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();
}

这篇关于使用防爆pressions获得获取财产Acessor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆