Document directory
- Object initializer
- Set the initial Timer
Object and set Initiator
When creating an object, you can include an object initializer or a set initializer to initialize the members of the created object or the elements of the newly created set. The initialization tool can simplify our code.
Object initializer
In the past, if a class is defined and the class is instantiated, we will do this as follows:
public class oec2003{ int x, y; public int X { get { return x; } set { x = value; } } public int Y { get { return x; } set { x = value; } }}
oec2003 o=new oec2003();o.X=2003;o.Y=2004;
Use object initializer
public class oec2003{ int x, y; public int X { get { return x; } set { x = value; } } public int Y { get { return x; } set { x = value; } }}var o=new oec2003{X=2003,Y=2004};
At the beginning of the object, the compiler uses the compiler to assign values to externally visible fields or attributes of the object in order, and calls the constructor in compilation or implicit mode, you can assign one or more values to a field or attribute.
Set the initial Timer
The Set initializer calls the elements in the initialization device in sequence. The following is an example of the set preliminary timer.
List<int> num = new List<int> { 0, 1, 2, 6, 7, 8, 9 };
The object type of the application set initiator must implement the system. Collections. Generic. icollections <t> interface and specify the specified T. The Set initiator calls icollection <t>. Add (t) for each specified element in sequence ).
The following Class records a person's personal information.
public class Oec2003Info{ string name; int age; List<string> phoneNumbers = new List<string>(); public string Name { get { return name; } set { name = value; } } public string Age { get { return age; } set { age = value; } } public List<string> PhoneNumbers { get { return phoneNumbers; } }}
Previous practices
var oec2003infos = new List<Oec2003Info>();var tmp1= new Oec2003Info();tmp1.Name = "oec2003";tmp1.Age=100;tmp1.PhoneNumbers.Add("tmp1.PhoneNumbers.Add("1592********");Oec2003Info.Add(tmp1);var tmp2 = new Oec2003Info();tmp2 .Name = "oec2003"; tmp2.Age=100;tmp2.PhoneNumbers.Add("1593********");tmp3.PhoneNumbers.Add("1594********");Oec2003Info.Add(tmp2);
Use object initializer
var oec2003infos= new List<Oec2003Info>{ new Oec2003Info { Name = "oec2003", Age=100; PhoneNumbers={"1591********","1592**********"} }, new Oec2003Info { Name = "oec2003", Age=100; PhoneNumbers = { "1593********","1594*********"} }};