The constructor is similar to the C ++ definition. Note that the system will not provide default constructor once the constructor with parameters in the Custom class does not define a constructor without parameters;
A static constructor is used to initialize static fields. It is called by the system after the class is created and before the class is instantiated;
The static constructor does not have public or other control operators, and does not return values and parameters;
Object initialization can be declared in two ways for Class Object Instantiation:
New Class (); // default constructor
Or:
New Class {x = 1, y = 2}; // It is also the default constructor;
Destructor, use ~ The Declaration contains no name but the function body. You cannot explicitly call the destructor. You can use another interface -- dispose interface, then, judge whether to call the destructor in The Destructor;
The above process is called the standard cleaning mode;
Comparison: constructor and destructor are both for instances. Static constructor is for static fields. Only instances have destructor. Static structures do not correspond to instances, so no destructor exists;
The readonly modifier of a field. Similar to the const feature can be implemented in the const function. Different values can be called in different constructors and cannot be changed once determined, unlike const, values must be fixed during initialization;
Therefore, readonly is equivalent to a const that is not common to other instances;
For example:
1 namespace ConsoleApplication1 2 { 3 class Test 4 { 5 readonly double PI = 3.14; 6 readonly int Num; 7 8 public Test(double x,double y) 9 {10 Num = 1;11 }12 public Test(int a,int b)13 {14 Num = 2;15 }16 public Test()17 {18 Num = 0;19 }20 public void printNum()21 {22 Console.WriteLine("{0}",Num);23 }24 }25 class MyClass26 {27 static void Main(string[] args)28 {29 Test t1 = new Test();30 Test t2 = new Test(1,2);31 Test t3 = new Test(1.0,2.0);32 t1.printNum();33 t2.printNum();34 t3.printNum();35 Console.ReadKey();36 }37 }38 }
C # Constructor