Static constructor:
(1) is used to initialize static fields, such as read-only fields.
(2) adding the static keyword, you can not add access modifier, because static constructors are private.
Static constructor (3) class in a given application domain execute at most once: only instance of the class to create a static or reference any member of the class was excited static constructor
(4) static constructors are not inherited, and can not be called directly.
(5) if the class contains the Main method for starting execution, the class's static constructor will be executed before the Main method calls.
(6) any static field with an initial value setting items, at the time of performing a static class constructor, first initializer performs those textual order.
(7) If not programmed static constructor, but this time with a static class field included in the initial value setting, then the compiler will automatically generate a default static constructor.
Classic example:
2 * static configuration made function exercises
. 3 * (. 1) ①②③ ...... order of performance
4 * (2) output: static A ()
. 5 * static B ()
. 6 * X-=. 1, the Y = 2
. 7 *** *********************************************** * / 8 the using the System; . 9 class A 10 { . 11 public static int X-; 12 is 13 is static A () // ④ after execution returns to ③ 14 { 15 X- = BY + . 1 ;
16 Console.WriteLine ( " static A () " );
. 17 } 18 is }
. 1920 isclass B21 is { 22 is public static int the Y = AX + . 1 ; // ③ A call to the static member, 23 // go to A static constructor ----> 24 25 static B () // ② If the static field with an initial value of the setting item, 26 // execute static class constructor, 27 // must first be performed in order of the text those initializer. 28 // Go initializer ----> 29 { 30
Console.WriteLine ( " static B () " );
31 is } 32 33 is static void Main () // ① program entry, 34 // if Main method for starting execution class contains, 35 // static class structure function will be executed before calling the Main method. 36 // Go static constructor B ----> 37 [ { 38 is Console.WriteLine ( " X-= {0}, the Y = {}. 1 " , AX, BY); // ⑤ output 39 Console.ReadLine (); 40 } 41 }
Reproduced in: https: //www.cnblogs.com/zhangchenliang/archive/2011/06/02/2070057.html