Object initializers and collection initializers (Collection initializers) Simplify our code to write a line of code that would otherwise have been written out. So in the use of LINQ, we don't write a LINQ expression in a complex way.
Object initializers
The use of the object initializer is simple: When an object is created from the new keyword, the desired proeprty is placed in {} after type name. Like what:
1class staff
2 {
3 public string Name { get; set; }
4 public int Age{get; set;}
5 public string Add;
6 public staff()
7 { }
8 public staff(int i, string s)
9 {
10 Name = s;
11 Age = i;
12 }
13 }
Using the object initializer
1Console.WriteLine("Initializer");
2 staff s1 = new staff(12, "sss") { Name = "GUOJUN" };
3 staff s3 = new staff(12, "sss") { Name = "GUOJUN", Age = 27,Add="HuBei" };
4 staff s2 = new staff { Name = "IORI", Age = 27 };
In the example above, we implement the creation and initialization of the Guojun object by means of a code (staff S1 = new staff ("SSS") {Name = "staff"};).
Attention:
The default constructor, such as the creation and initialization of S2, is implicitly invoked when the object initializer is used.
When you use the object initializer, you can also specify that any custom constructors be invoked. (for example, S1, S3 creation and initialization).
You can assign values to multiple (not necessarily all) properties at once.
1staff s1 = new staff(12, "sss") { Name = "GUOJUN" };
2staff s3 = new staff(12, "sss") { Name = "GUOJUN", Age = 27,Add="HuBei" };
C # 3.x These feature are only based on a new feature of the programming language layer, which is implemented by adding some auxiliary code to the language compiler corresponding to the compilation process. By compiling we look at what becomes:
1public static void fnInitializer()
2{
3 Console.WriteLine("Initializer");
4 staff <>g__initLocal3 = new staff(12, "sss");
5 <>g__initLocal3.Name = "GUOJUN";
6 staff s1 = <>g__initLocal3;
7 staff <>g__initLocal4 = new staff(12, "sss");
8 <>g__initLocal4.Name = "GUOJUN";
9 <>g__initLocal4.Age = 0x1b;
10 <>g__initLocal4.Add = "HuBei";
11 staff s3 = <>g__initLocal4;
12 staff <>g__initLocal5 = new staff();
13 <>g__initLocal5.Name = "IORI";
14 <>g__initLocal5.Age = 0x1b;
15 staff s2 = <>g__initLocal5;
16 Console.WriteLine(s1.Name);
17 Console.WriteLine(s1.Age);
18 Console.WriteLine (s2.Name);
19}