C #3.0 new feature learning notes (1): object set Initiator

Source: Internet
Author: User

Object set Initiator

I. Introduction
(1) object initialization

If a class has public fields, you can use the following code to initialize these fields when creating an object instance of the class;

Public class PersonInfo
{
Public string id;
Public string name;
Public string description;
}

PersonInfomy = new PersonInfo ();
My. id = "9527 ";
My. name = "Jack Dong ";
My. description = "I am a Software Engineer ";

In C #3.0, a simpler method is provided to initialize these public variables. The Code is as follows:

PersonInfomy = new PersonInfo
{
Id = "9527 ",
Name = "Jack Dong ";
Description = "I am a Software Engineer ";
};

The code above is written as a constructor with parameters, but this does not call the constructor of PersonInfo (because PersonInfo does not contain the constructor with three parameters ),

It's just a magic of C # compiler. In fact, the above Code is still the same as the method used to initialize fields after compilation. It just looks simpler in syntax (at least not

Write so many my ).

(2) Set Initialization

The Set initialization does not need to use the ADD method. Previously, for example, to construct a List, all of them need to be used now.

In C #3.0, the initialization method for the Collection class is improved (the initialization method is similar to an array ). Unfortunately, this initialization method only supports the use of generic collection classes, that is,

This initialization method can be used only when System. Collections. Generic. Cllection <T> is implemented. The Code is as follows:

List <string> myList = new List <string> {"a", "B", "c "};
Foreach (string str myList)
{
TextBox1.AppendText (str );
}

Ii. Notes

To use this method to initialize an object, it must be a public field (not a field of protected, private, or default modifier ).

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.