The anonymous type is a mechanism that automatically generates a type based on the initialization list during initialization. The object initializer is used to create an anonymous object. For example:
VaR OEC = new {name = "oec2003", age = 100}
The VaR and new keywords are used in the statement for object creation. The VaR keyword is used to declare an anonymous object name. Var and object are different, and they are strongly typed, this serves as a placeholder. during compilation, the compiler will deduce the actual type. The new keyword is directly followed by a pair of braces, not the type name, because the anonymous type name is automatically generated by the compiler during compilation. The name and age in braces are anonymous type attributes. You can see that they are directly assigned after the name and age, and the type is not specified. The compiler will also infer their type, for example, after compilation, the name type is inferred to be string type, and the age type is inferred to be int type. Therefore, we can see that the anonymous type brings us a lot of flexibility and flexibility, and it also makes the code hard to understand. After the above Code is compiled, code similar to the following will be generated:
Class anonymous1 {private int _ name = oec2003; private int _ age = 100; Public int A {get {return _ name;} set {_ name = value ;}} public int B {get {return _ age;} set {_ age = value ;}}}
In the same program, if the names, types, and sequence of object initiators of different anonymous types are the same, different instances of the same anonymous type will be generated, as shown below:
VaR oec1 = new {name = "oec2003", age = 100} var oec2 = new {name = "oec2004", age = 200} oec1 = oec2
We can access Anonymous members in this way.
VaR OEC = new {name = "oec2003", age = 100} string name = OEC. Name; int age = OEC. Age