A static constructor is a new feature of C #, which seems to be seldom used. But we need to use it when we want to initialize some static variables. This constructor belongs to the class, not to the instance where it belongs, meaning that the constructor will only be executed once . This is called automatically by. NET before the first instance is created or any static members are referenced.
class simpleclass{ // static constructor static simpleclass () { // }}
There are a few things to keep in mind when using static constructors:
1. Static constructors have neither access modifiers nor parameters. Because it is. NET calls, so modifiers like public and private are meaningless.
2, is when the first class instance is created or any static member is referenced. NET will automatically call the static constructor to initialize the class, which means that we cannot call the static constructor directly, and we cannot control when the static constructor is executed.
3. A class can have only one static constructor.
4. Parameterless constructors can coexist with static constructors. Although the parameter list is the same, one belongs to the class and one belongs to the instance, so there is no conflict.
5, run up to one time only.
6. Static constructors cannot be inherited.
7. If a static constructor is not written, and the class contains a static member with an initial value set, the compiler automatically generates a default static constructor.
A class can have only one static constructor, which cannot have access modifiers, cannot take any arguments, cannot be called directly, only in:
1 When you create a class instance that contains a static constructor
2 when accessing static members that contain static constructors
The static constructor is called first, and its static constructor is called only once, no matter how many instances of the class are created.
Static classes contain only static members and cannot be instantiated, although you can have a static constructor as mentioned above.
Citation Links:
C #-static classes and static constructorssome notes on C # static constructors
About static classes and static constructors for C #