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;
答案 0 :(得分:1)
我认为是。一个证据是,如果将在CompileGetValueExpression
中创建的表达式作为字符串转储,它将输出i => (i.prop1 As Object)
。
尝试修改CompileGetValueExpression
的最后一行
Expression.Lambda<Func<T, object>>(convert, instance).ToString();