private static Func<object, object> MakeGetFunc2(PropertyInfo propertyInfo) { var getter = typeof(PropertyInfo).GetMethod("GetValue", new Type[] { typeof(object) }); var propertyInst = Expression.Constant(propertyInfo); var paramInst = Expression.Parameter(typeof(object)); var bodyExp = Expression.Call(propertyInst, getter, paramInst); var blockExp = Expression.Block(typeof(object), new ParameterExpression[] { paramInst }, bodyExp); var result = Expression.Lambda<Func<object, object>>(blockExp, paramInst).Compile(); return result; }
上面方法的目的是:
基于propertyInfo,调用GetValue方法。但执行时报告未传递参数。
public class T { public int Age { get; set; } } static void Main(string[] args) { var property = typeof(T).GetProperty("Age"); var getter = MakeGetFunc2(property); getter(new T()); }
//var blockExp = Expression.Block(typeof(object), new ParameterExpression[] { paramInst }, bodyExp); var result = Expression.Lambda<Func<object, object>>(bodyExp, paramInst).Compile();
本质上是var blockExp = Expression.Block(typeof(object), new ParameterExpression[] { paramInst }, bodyExp);这里的错误,paramInst一共作为了两次形参在外层的LambdaExpression和里层的BlockExpression中,由于作用域的原因,new T()对象只传到了外层,这里可以去掉Expression.Block中new ParameterExpression[] { paramInst },让内层可捕获到传入的这个对象
好的,我试下。
另外一个问题,也拜托下:http://q.cnblogs.com/q/79990/