The main function is to set the initialization of static fields in the type. The Type constructor does not have to be defined in the class, but can have only one. Example:
Copy codeThe Code is as follows: class SomeType {
Static SomeType (){}
}
When compiling a method, the jit compiler will view the types referenced by the Code. If any type defines the Type constructor, the jit compiler checks whether the current AppDomain has executed this Type constructor. If no constructor is executed, it returns the result directly without executing it again. In a multi-threaded environment, multiple methods may execute the same method at the same time. CLR wants one Type constructor in each AppDomain to be executed only once. When the Type constructor is called, solve this problem by using the mutex thread synchronization lock.
Only static fields of the type can be accessed in the Type constructor.
Code inline initialization field:
Copy codeThe Code is as follows: class SomeType
{
Static int x = 5;
}
Equivalent
Copy codeThe Code is as follows: class SomeType
{
Static int x;
Static SomeType ()
{
X = 5;
}
}
Also:Copy codeThe Code is as follows: class SomeType
{
Static int x = 3;
Static SomeType ()
{
X = 5;
}
}
EquivalentCopy codeThe Code is as follows: class SomeType
{
Static int x;
Static SomeType ()
{
X = 3;
X = 5;
}
}
Although c # does not allow the inline initialization syntax for its instantiated fields, but static fields are acceptable. The above code can run the same way as changing the class to struct,
The main reason is that the value type can define the parameter-free constructor, but the parameter-free constructor cannot be defined.