Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

c# - Property selector Expression<Func<T>>. How to get/set value to selected property

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...