本文介绍了新对象的表达式树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I'm trying to dynamically create an expression for a new object but I can't figure out how to do it.
void DoWork(Type t)
{
//do some work to figure out which properties I want to use
List<PropertyInfo>() props = (from p in t.GetProperties()
where p.HasAttribute(MyAttribute)
select p).ToList();
//now I want to create a lambda expression that's like: (x=> new {x.Prop1, x.Prop2, ...})
//for each property in the list props
//create parameter
var param = Expression.Parameter(t,"t");
//get list of expressions for properties
var initValues = (from p in props
select Expression.PropertyOrField(param, p.Name)).ToList();
//build expression body
Expression body = Expression. //I have no idea what to do here
//create lambda
dynamic propLambda = Expression.Lambda(body, param);
//use it! MyFunction( x=> new {x.Prop1, x.Prop2,...});
MyFunction(lambda);
}
推荐答案
void DoWork(Type t)
{
var param = Expression.Parameter(t, "t");
var returnValue = Expression.New(t);
var initValues = from p in t.GetProperties()
where p.HasAttribute(MyAttribute)
let value = Expression.Property(param, p)
select Expression.Bind(p, value);
var body = Expression.MemberInit(returnValue, initValues);
var propLambda = Expression.Lambda(body, param);
MyFunction(propLambda);
}
这篇关于新对象的表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!