First, the original author did not provide the source code. This code was written based on the author's original intent. This includes the Lambda, LINQ, Expression Tree, reflection, and Tuple I mentioned earlier.
Combining a lot of new features is also a good example. It can be used as a question, haha.
The problem arises from: If you have a lot of examples of various classes, how do you change the attributes of all these classes?
Method 1: using traditional reflection, the code is very simple, that is, getting an instance of a class, then getting the class type, getting all the attributes from the type,
Then obtain the attribute value of the instance and print it out.
1 public void DumpReflection (object [] objs)
2 {
3 for (int I = 0; I <objs. Length; I ++)
4 {// obtain all attributes of the object Type
5 PropertyInfo [] pi = objs [I]. GetType (). GetProperties ();
6 for (int j = 0; j <pi. Length; j ++)
7 {// get the property value and print it
8 Console. WriteLine (pi [j]. Name + ":" + pi [j]. GetValue (objs [I], null ));
9}
10}
11}
Method 2: Use lambda and the Expression Tree to obtain all the attribute enumeration delegates of the class, and then use the delegate to directly obtain the attributes.
Use LINQ to enumerate all attributes and compile them into lambda expressions. Then call each lambda expression to obtain the attributes of the class.
According to the author, the data volume significantly improves the performance.
1 //##################################### ########
2 //
3 // dump Hundreds of object, using reflection linq and lambda and delegate generic.
4 //
5 //##################################### #######
6 public void DumpLambda (object [] objs)
7 {
8 for (int I = 0; I <objs. Length; I ++)
9 {// If C #4.0 is used, use the system to provide tuple.
10 Tuple [] t = GetTuple (objs [I]. GetType ());
11 for (int j = 0; j <t. Length; j ++)
12 {// use a generic delegate to create a delegated instance.
13 Func <object, object> temp = (Func <object, object>) t [j]. Delegate;
14 Console. WriteLine (t [j]. Name + ":" + temp (objs [I]);
15}
16}
17}
18
19 private Tuple [] GetTuple (Type t)
20 {
21 // create lambda: (o) => (t) o). pi; (pi is a specific attribute of the type)
22 Tuple [] dRet = (from pi in t. GetProperties () // traverse each attribute
23 let o = Expression. Parameter (typeof (object), "o") // set Lambda Expression Parameters
24 select new Tuple (pi. name, Expression. lambda (Expression. convert (Expression. property (Expression. convert (o, t), pi), typeof (object), o ). compile ())). toArray ();
25 // returns the tuple class.
26 return dRet;
27}
28
29 public class Tuple
30 {
31 public string Name {get; set ;}
32 public Delegate {get; set ;}
33 public Tuple (string name, Delegate d)
34 {
35 this. Name = name;
36 this. Delegate = d;
37}
38}
The above example is very understandable, combining a lot of C # knowledge and features.
Download: Code