Object/set Initiator

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.