属性选择器表达式来; Func键< T>> ;.如何获取/设置值选定属性 [英] Property selector Expression<Func<T>>. How to get/set value to selected property
问题描述
我有我想在这样的方式来构造一个对象:
无功富=新FancyObject(客户,C = GT; c.Email); //客户有email属性
我应该如何申报的第二个参数?
如何将访问选定的setter / getter属性将类似于代码?
UPD。有在具有电子邮件属性模型几个实体。所以,可能是签名将是这样的:
公共FancyObject(实体保持架,表达式来; Func键< T>>选择器)
和构造函数调用
无功富=新FancyObject(客户,()=> customer.Email);
参数将是表达式来; Func键<客户,串>>选择
。阅读它可以通过平编译:
Func键<客户,串> FUNC = selector.Compile();
即可进入 FUNC(客户)
。分配是棘手;简单的选择您可能希望你可以简单地分解为:
VAR道具=(的PropertyInfo)((MemberExpression)selector.Body )。会员;
prop.SetValue(客户,为newValue,NULL);
但更复杂的表达式要么需要人工树散步,或某些4.0表达式节点类型
表达式来; Func键<客户,串>>电子邮件
=卡斯特= GT; cust.Email;
变种为newValue = Expression.Parameter(email.Body.Type);
VAR分配= Expression.Lambda<作用<客户,串>>(
Expression.Assign(email.Body,为newValue),
email.Parameters [0],为newValue);
VAR吸气= email.Compile();
VAR二传手= assign.Compile();
I have an object that I want to be constructed in such manner:
var foo = new FancyObject(customer, c=>c.Email); //customer has Email property
How should I declare second parameter?
How the code that will access selected property setter/getter will look like?
Upd. There are several entities in the model that has Email property. So probably the signature will looks like:
public FancyObject(Entity holder, Expression<Func<T>> selector)
and the constructor call
var foo = new FancyObject(customer, ()=>customer.Email);
The parameter would be an Expression<Func<Customer,string>> selector
. Reading it can be via flat compile:
Func<Customer,string> func = selector.Compile();
then you can access func(customer)
. Assigning is trickier; for simple selectors your could hope that you can simply decompose to:
var prop = (PropertyInfo)((MemberExpression)selector.Body).Member;
prop.SetValue(customer, newValue, null);
But more complex expressions would either need a manual tree walk, or some of the 4.0 expression node-types:
Expression<Func<Customer, string>> email
= cust => cust.Email;
var newValue = Expression.Parameter(email.Body.Type);
var assign = Expression.Lambda<Action<Customer, string>>(
Expression.Assign(email.Body, newValue),
email.Parameters[0], newValue);
var getter = email.Compile();
var setter = assign.Compile();
这篇关于属性选择器表达式来; Func键< T>> ;.如何获取/设置值选定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!