C # Summary of Advanced Programming
1. C # static Constructor
1. The static constructor neither has an access modifier nor a parameter. Because it is called by. NET, modifiers such as public and private are meaningless.
2. When the first class instance or any static member is referenced ,. NET will automatically call the static constructor to initialize the class. That is to say, we cannot directly call the static constructor, so we cannot control when to execute the static constructor.
3. A class can have only one static constructor.
4. A non-parameter constructor can coexist with a static constructor. Although the parameter list is the same, one belongs to the class and the other belongs to the instance, so there is no conflict.
5. Run only once at most.
6. Static constructors cannot be inherited.
7. If no static constructor is written and the class contains static members with an initial value, the compiler automatically generates the default static constructor.
Public class A {public static readonly int x; static A () {x = B. y + 1 ;}} class B {public static int y =. x + 1; static void Main (string [] args) {Console. writeLine ("x: {0}, y: {1 }. ", A. x, y); Console. ReadLine ();}}
// X = 1, y = 2.
The default value of global variables of simple value type is 0. Because the entry function is in Class B, the program first loads B. Because y is a static member of B, when A class is loaded, the value of y is calculated. However, it is found that the value of y is obtained by assigning values. The value of x is used on the right side of the equal sign, and the value of x is calculated immediately, x is initialized through the static constructor of Class A, and B's Y is referenced during this period. At this time, the value of y is still 0 (because the value assignment statement of y has not been executed yet, so its value is still the default value), get x = 0 + 1 = 1, continue to assign a value for y to get y = x + 1 = 2.