1. Object Initiator
Object initialization is generally performed in its constructor, but sometimes we need to manually assign values, such
//传统的方式 Person p1 = new Person(); p1.Name = "小李"; p1.Age = 23; //对象初始化器 Person p2 = new Person() {Name="小明",Age=26 };
Decompilation code:
We can see that the role of the Object initiator is to create a temporary object of the person type.<> G_initlocal0And then assign the temporary object to the created object P2. Therefore, the CLR underlying layer does not perform any additional operations on the object initializer. All these operations are completed by the C # compiler.
From the Il code, I can also see that these two initialization methods are eventually compiled into the same il code, but with the object initializer, the compiler creates a temporary object.
2 set Initiator
List<Person> list1 = new List<Person>(); list1.Add(new Person() { Name = "小李", Age = 26 }); list1.Add(new Person() { Name = "小方", Age = 23 }); List<Person> list2 = new List<Person>() { new Person (){ Name="小涛",Age=24}, new Person (){ Name="小王",Age=21} };
The decompiled results show that the compiled Il is also a temporary set object generated by the compiler, and then the add method is called to add the set element. Finally, the temporary object is assigned to the created object.
Object/set Initiator