Expression.Lambda getter函数编译

时间:2019-03-07 03:42:29

标签: c#

代码:

static Func<T,object> CompileGetValueExpression<T>(PropertyInfo propertyInfo)
{
    var instance = Expression.Parameter(propertyInfo.DeclaringType, "i");
    var property = Expression.Property(instance, propertyInfo);
    var convert = Expression.TypeAs(property, typeof(object));
    return Expression.Lambda<Func<T,object>>(convert, instance).Compile();
}

例如

void Main()
{
    var data = new Test{prop1 = 1};
    var type = data.GetType();
    var prop = type.GetProperties().First();
    var function = CompileGetValueExpression<Test>(prop);
    var result = function(data); //result:1
}

class Test{
    public int prop1 { get; set; }
}

问题

此表达式函数是否完全等同于以下方法?

object GetterFunction(Test i) => i.prop1 as object; 

1 个答案:

答案 0 :(得分:1)

我认为是。一个证据是,如果将在CompileGetValueExpression中创建的表达式作为字符串转储,它将输出i => (i.prop1 As Object)

尝试修改CompileGetValueExpression的最后一行

Expression.Lambda<Func<T, object>>(convert, instance).ToString();