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 ).