(1) For initialization of static fields, read-only fields, and so on.
(2) Add the static keyword and cannot add an access modifier because the static constructor is private.
(3) The static constructor of a class executes at most once in a given application domain: the static constructor is fired only if an instance of the class is created or any static members of the reference class are referenced
(4) A static constructor is not inheritable and cannot be invoked directly.
(5) If the class contains the main method used to start execution, the static constructor of the class is executed before the main method is called. Any static field with an initializer, the static constructor of the class is executed in the order of the text in which the initializer is executed.
(6) If a static constructor is not written and the class contains a static field with an initializer, the compiler automatically generates the default static constructor.
The following is further illustrated with the example code:
Copy Code code as follows:
/**************************************************
* Static constructor Exercises
* (1) ①②③ ... In order of execution
* (2) Output result: Static A ()
* Static B ()
* X = 1, Y = 2
***************************************************/
Using System;
Class A
{
public static int X;
Static A ()//④ returns to ③ after execution
{
X = b.y + 1;
Console.WriteLine ("Static A ()");
}
}
Class B
{
public static int Y = a.x + 1; ③ called the static member of A,
Go to a static constructor---->
Static B ()//② If the field with the initializer is statically
When the static constructor of the class is executed,
You must first perform those initializers in the order of text.
Go to initializer---->
{
Console.WriteLine ("Static B ()");
}
static void Main ()//① program entry,
If the class contains the Main method used to start execution,
The static constructor for the class is executed before the Main method is called.
Go to B's static constructor---->
{
Console.WriteLine ("X = {0}, Y = {1}", a.x, b.y);//⑤ output result
Console.ReadLine ();
}
}