【问题标题】:Using Expressions to get a Get Acessor of a property使用表达式获取属性的 Get Acessor
【发布时间】: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();

}

不幸的是,我不得不将&lt;Object,Object&gt; 作为泛型参数,因为有时我会得到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&lt;Object,Object&gt;

【问题讨论】:

    标签: c# api reflection lambda expression


    【解决方案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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多