Constructor and object initializer
Constructor:Used to instantiate an object.
Generally, a default no-argument constructor exists in the class or struct. If we manually write a constructor with parameters in the class, the constructor without parameters will be overwritten, but the constructor will not be overwritten, even if we have written a construction method with parameters in the struct, the construction method without parameters can still be used.
[When using the singleton mode, we can write a private constructor to prevent the class from being instantiated again in other classes and enhance the robustness of the Code .]
Static constructor:Used to initialize static members.
A class can have only one static constructor without any access modifiers and no parameters.
The static constructor initializes the static members in the class before the program creates the first instance or references any static members.
Object initializer:In a class, we usually use constructor to assign values to fields, attributes, and other Members to complete object initialization. However, when there are many fields and attributes in a class, it is impossible to define the constructor for various situations. In this case, we can use the "Object initiator" to assign values to fields and attributes, object initialization is completed.
The syntax format is as follows:
1 public class Test 2 {3 private void Start () 4 {5 AA B = new AA () {a = 1, B = true}; 6 AA a = new AA () {B = true, c = "str"}; 7} 8} 9 public class AA10 {11 public int a; 12 public bool B; 13 14 private string _ c; 15 public string c16 {17 get {return _ c;} 18 set {_ c = value;} 19} 20}