Entity classes:
public class Student
{public
int Id {get; set;}
public string Name {get; set;}
Public string[] Multiplecareers {get; set;}
Public Location Location {get; set;}
}
public class Location
{public
int Row {get; set;}
public int Col {get; set;}
}
Program.cs Code:
Class Program {private static void Main (string[] args) {Object student = new Student {Id = 1, Name = "Zhang San", Multiplecareers =new string[]{"Teacher"
, "Programmer", "writer", "Painter"}, Location = new Location {Row = 10,
Col = 20}};
Visitproperties<student> (Student); ///<summary>///Recursive access to properties of objects of unknown type///</summary>///<typeparam na Me= "T" ></typeparam>///<param name= "obj" ></param> private static void Visitpropertie S<t> (Object obj) {type type = obj.
GetType ();
ParameterExpression paraexpression = Expression.parameter (typeof (T), "Object"); foreach (PropertyInfo prop in type.) GetProperties ()) {Type Proptype = Prop. PrOpertytype; The expression tree that determines whether the base type or string//access method is: obj =>obj.
Property if (proptype.isprimitive | | proptype = = typeof (String)) {
Visitproperty<t> (obj, prop, paraexpression, paraexpression);
} else {//the expression tree for the access method is: Obj=>obj.otherobj.property. Console.WriteLine ("Not primitive property:" + Prop.)
Name); Type Othertype = Prop.
PropertyType;
Memberexpression memberexpression = Expression.property (paraexpression, prop);
Access all public properties in the Obj.otherobj foreach (PropertyInfo otherprop in Othertype.getproperties ())
{visitproperty<t> (obj, Otherprop, memberexpression, paraexpression); } Console.WriteLine ("--------------------------------");
}///<summary>///execution expression tree is: Obj=>obj. Calculation of property or Obj=>obj.otherobj.property///</summary>///<param name= "Instanceexpression" &G
t; representation of the expression tree of the Obj object of the final Access property </param>///<param name= "parameterexpression" > type T the expression of the tree of parameter expressions </param> private static void Visitproperty<t> (Object obj, PropertyInfo prop, Expression instanceexpression, Parameterexpre Ssion parameterexpression) {Console.WriteLine ("Property name:" + Prop.)
Name);
Memberexpression memexpression = Expression.property (instanceexpression, prop); Implement type conversions, such as converting the int type of ID to type object to facilitate the following versatility Expression objectexpression = Expression.convert (memexpression, Typeo
F (object)); Expression<func<t, object>> lambdaexpression = expression.lambda<func<t, object>> (
Objectexpression, parameterexpression);
Print an expression tree Console.WriteLine ("Expression tree:" + lambdaexpression);
Func<t, object> Func = Lambdaexpression.compile (); Console.WriteLine ("Value:" + func ((T) obj)); Print out the resulting property value}}
run the results as shown in figure: