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