C #3.0: object collection Initiator

Source: Internet
Author: User

When writing some entity classes, we often think about constructor for a long time. Besides a non-argument constructor, how many constructor do we need to write? Which parameters need to be initialized. Now you no longer need to worry about it. C #3.0 provides the object set initializer for you:

///  
/// Books
///  
Public   Class Book
{
///  
/// Book name
///  
Public   String Title { Get ; Set ;}
///  
/// Unit Price
///  
Public   Float Price { Get ; Set ;}
///  
/// Author
///  
Public   String Author { Get ; Set ;}
///  
/// ISBN No.
///  
Public   String ISBN { Get ; Set ;}
}
// Object initializer
Book =   New Book {Title = " Inside com " , ISBN = " 123-456-789 " };

Now you need to initialize a few objects without the following:

Public Book (): This ( "" )
{
}
Public Book ( String Title ): This (Title, 0 )
{
}
Public Book ( String Title, Float Price ): This (Title, price, "" )
{
}
Public Book ( String Title, Float Price, String ISBN)
{
This. Title=Title;
This. Price=Price;
This. ISBN=ISBN;
}

The constructor of this string is used to cope with different initialization conditions. Okay. Let's take a look at what the object initializer compiler has done for us in the future? Decompilation with reflectorProgramSet:

Book <> G _ initlocal0 =   New Book ();
<> G _ initlocal0.title =   " Inside com " ;
<> G _ initlocal0.isbn =   " 123-456-789 " ;
Book =   <> G _ initlocal0;

C # The Compiler generates a new local variable <> G _ initlocal0. Call the default non-argument constructor of book to initialize it and assign values to its attributes, finally, assign this local variable to book. Here, we should think that to use the object initializer, the object must have a construction method without parameters, if you write a constructor for this method and overwrite its default constructor without providing a new constructor, so it won't pass the compilation by using the object initializer (but I cannot figure it out. Why don't the C # compiler generate such a strange local variable name, and why don't I use the book directly ). Like the followingCodeNot better:

Book =   New Book ();
Book. Title =   " Inside com " ;
Book. ISBN =   " 123-456-789 " ;

Later, I found that I compiled it in debug mode and changed it to the release mode as follows:

 
Book <> G _ initlocal0 =NewBook ();<> G _ initlocal0.title ="Inside com";<> G _ initlocal0.isbn ="123-456-789";

 

 

Optimized. The object initializer is introduced above. What is the set initializer?

Ilist < Book > Books =   New List < Book > ();
// The object initializer is used here.
Books. Add ( New Book {Title =   " Inside com " , ISBN =   " 123-456-789 " , Price = 20 });
Books. Add ( New Book {Title =   " Inside C # " , ISBN =   " 123-356-d89 " , Price = 100 });
Books. Add ( New Book {Title =   " LINQ " , ISBN =   " 123-d56-d89 " , Price =   120 });

This code is not much written. In fact, it may be more complicated than this. With C #3.0, we all want to laugh at our sleep:

Ilist < Book > Books =   New List < Book > {
New Book {Title =   " Inside com " , ISBN =   " 123-456-789 " , Price = 20 },
New Book {Title =   " Inside C # " , ISBN =   " 123-356-d89 " , Price = 100 },
New Book {Title =   " LINQ " , ISBN =   " 123-d56-d89 " , Price =   120 }
};

Let's take a look at the code generated by the C # compiler for us, just like we did in the past:

List < Book >   <> G _ initlocal0 =   New List < Book > ();
Book <> G _ initlocal1 =   New Book ();
<> G _ initlocal1.title =   " Inside com " ;
<> G _ initlocal1.isbn =   " 123-456-789 " ;
<> G _ initlocal1.price = 20f;
<> G _ initlocal0.add ( <> G _ initlocal1 );
Book <> G _ initlocal2 =   New Book ();
<> G _ initlocal2.title =   " Inside C # " ;
<> G _ initlocal2.isbn =   " 123-356-d89 " ;
<> G _ initlocal2.price = 100f;
<> G _ initlocal0.add ( <> G _ initlocal2 );
Book <> G _ initlocal3 =   New Book ();
<> G _ initlocal3.title =   " LINQ " ;
<> G _ initlocal3.isbn =   " 123-d56-d89 " ;
<> G _ initlocal3.price = 120f;
<> G _ initlocal0.add ( <> G _ initlocal3 );

From the code above, the compiler automatically calls the list non-argument constructor, instantiates the books one by one, and adds them one by one, which is no different from our original practice. However, this is what the compiler does for us, so it saves us a lot of coding work.

The object set initializer is finished. Some people may say, isn't it syntx sugar? What is it. Yes, it is indeed a syntactic sugar. In the early days of compiler development, compiler scientists have been trying to optimize the code generated by the compiler. At this time, the compiler mainly optimizes the machine because the time of the machine was very valuable, machine computing speed is not fast. Today we have enough good machines (but it doesn't mean that we can write programs with no focus on performance), and as a software developer, it is much more valuable than the machine's time, so today's compiler is also being optimized to people, fromProgramming LanguageIn terms of the development path, today's programming language is more advanced and user-friendly than yesterday's language. We only need to write less code, more human-thinking code, as long as we focus on the focus of our values. Give it to the compiler for physical work.

Additional:

At the beginning, I thought that the object set initializer may be useless. Don't you just need to reduce a little bit of Code. For such simple initialization work, most code generators can work on it. Later, when studying the anonymous type, I suddenly found that, without this object initializer, the anonymous type would be more complex? Or is it hard to implement?

VaR test = new {key = "test", value = "test"}; What should I do if there is no object initializer?

 

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.