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();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…