Today, I spent some time summing up the usage of the static constructor. I hope you can give some advice. Thank you!
-
The static constructor neither has an access modifier nor a parameter.
-
If a static constructor is not compiled, and the class contains a static field with an initial value, the compiler automatically generates the default static constructor.
-
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.
-
If the class contains the Main method used to start execution, the static constructor of the class will be executed before the Main method is called.
-
If the static field in the class carries initialization, the initialization statement of the static field runs before the static constructor.
-
A class can have only one static constructor.
-
Constructors without parameters can coexist with static constructors. Although the parameter list is the same, one belongs to the class and the other belongs to the instance, so there is no conflict.
-
Run only once at most.
-
Static constructors cannot be inherited.
-
The sample code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace Test
{
Class Program
{
Public static int X;
// In Step 2, because Program. X is called in step 1, the static constructor is automatically called to initialize the class before the first instance is created or any static member is referenced.
Static Program ()
{
X = B .Y + 1; // at this time, B .Y = 0;
Console. WriteLine ("static ()");
}
}
Class B
{
/* Step 1
If the class contains the Main method used to start execution, the static constructor of the class will be executed before the Main method is called.
If the static field in the class carries initialization, the initialization statement of the static field runs before the static constructor. */
Public static int Y = Program. X + 1;
Static B ()
{
Console. WriteLine ("static B ()");
}
Static void Main ()
{
Console. WriteLine ("X = {0}, Y = {1}", Program. X, B .Y );
Console. ReadLine ();
}
}
}
The running result is:
Static ()
Static B ()
X = 1, Y = 2