Using expression tree to access the property names and values of a class

Source: Internet
Author: User

Expressions tree expression is a relatively important feature in LINQ, and it is helpful to have a deep understanding of LAMDA and to evaluate expressions.

The following is the use of expression<func<object>>[] to get the operands or member names and values in func<object>.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Linq.Expressions;usingSystem.Reflection;namespaceexpressiontree{classProgram {Static voidMain (string[] args) {MyClass CLS=NewMyClass () {Memo ="ffffddddd", Name ="DFDF", age = - }; Dictionary<string,string> dic = GetProps (() = cls. Memo, () =CLS.            Age); foreach(keyvaluepair<string,string> Iteminchdic) {Console.WriteLine (item. Key+"="+item.            Value);        } console.read (); }        Staticdictionary<string,string> GetProps (paramsExpression<func<object>>[] funcs) {Dictionary<string,string> dic =Newdictionary<string,string>(); Memberexpression member=NULL; Unaryexpression unary=NULL; foreach(Expression<func<object>> FuncinchFuncs) {Unary= Func. Body asunaryexpression; if(Unary! =NULL) {Member= unary. Operand asmemberexpression; }                Else{Member= Func. Body asmemberexpression; } PropertyInfo Prop= member. Member asPropertyInfo; ObjectValue =Func.compile ().                Invoke (); Dic. ADD (Prop.            Name, convert.tostring (value)); }            returndic; }    }    classMyClass { Public stringName {Get;Set; }  Public intAge {Get;Set; }  Public stringMemo {Get;Set; } }}

Using expression tree to access the property names and values of a class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.