Object initializer, object initialization
1. Why is object initializer used?
C #3.0 provides an object initializer. To facilitate the programmer to control the attributes to be initialized at initialization, the programmer does not need to modify or add constructor when the attributes are not modified at the time of initialization.
2. How to Use the object Initiator
The class is defined as follows:
public class Person { private string name; public string Name { get { return name; } set { name = value; } } private string sex; public string Sex { get { return sex; } set { sex = value; } } private string age; public string Age { get { return age; } set { age = value; } }
The client code is as follows:
Class Program {static void Main (string [] args) {Person person = new Person {Name = "Qian", Age = "27", Sex = "female "}; string s = String. format ("Name: {0}, age: {1}, Gender: {2}", person. name, person. age, person. sex); // string s = person. getPersonDetail (); Console. writeLine (s); Console. readLine ();}}
Execution result:
3. Precautions for using the object initializer
The class of the object to be initialized must have a default non-parameter constructor. If a constructor overwrites a non-parameter constructor, you must explicitly define a non-parameter constructor to compile and execute the constructor smoothly.
I have defined a constructor.
public Person(string name, string age, string sex) { this.name = name; this.age = age; this.sex = sex; }
Client call
Class Program {static void Main (string [] args) {Person person = new Person {Name = "Qian", Age = "27", Sex = "female "}; string s = String. format ("Name: {0}, age: {1}, Gender: {2}", person. name, person. age, person. sex); // string s = person. getPersonDetail (); Console. writeLine (s); Console. readLine ();}}
As a result, no constructor compiler displays
Compilation is successful only when no-argument constructor is added to the Person class.
public Person() { } public Person(string name, string age, string sex) { this.name = name; this.age = age; this.sex = sex; }