我有一个List< string>的对象我想构建一个表达式树,为这个属性添加一个值,但我想指定要通过Func添加的值.
目前我试试这个……
public static Action<T> CreateMethodAddobjectToList<T,C>(this Type type,string property,Func<C> ctorFunction) { PropertyInfo fIEldInfo = type.GetProperty(property); if (fIEldInfo == null) { return null; } ParameterExpression targetExp = Expression.Parameter(type,"target"); MemberExpression fIEldExp = Expression.Property(targetExp,property); var method = fIEldExp.Type.getmethod("Add",BindingFlags.Public | BindingFlags.Instance); Expression<Func<C>> ctorExpression = () => ctorFunction();// but this doesnt work because I can't use the ctorExpression in this way var callExp = Expression.Call(fIEldExp,method,ctorExpression); var function = Expression.Lambda<Action<T>>(callExp,targetExp).Compile(); return function; }
电话看起来像
var dummyObject = new DummyObject { IntProperty = 5 }; Action<DummyObject> setter = typeof (DummyObject).CreateMethodAddobjectToList<DummyObject,string>("StringList",() => "Test" );解决方法 您可以将ctorFunction更改为Expression< Func< C>>然后在生成的 *** 作中调用它:
public static Action<T> CreateMethodAddobjectToList<T,Expression<Func<C>> createExpr){ PropertyInfo fIEldInfo = type.GetProperty(property); if (fIEldInfo == null) { return null; } ParameterExpression targetExp = Expression.Parameter(type,"target"); MemberExpression fIEldExp = Expression.Property(targetExp,property); var method = fIEldExp.Type.getmethod("Add",BindingFlags.Public | BindingFlags.Instance); var valueExpr = Expression.Invoke(createExpr); var callExpr = Expression.Call(fIEldExp,valueExpr); var function = Expression.Lambda<Action<T>>(callExpr,targetExp).Compile(); return function;}总结
以上是内存溢出为你收集整理的c# – 对表达式树使用lambda返回值全部内容,希望文章能够帮你解决c# – 对表达式树使用lambda返回值所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)