The main purpose is to set the initialization of static fields in the type. Type constructors are not necessarily defined in a class, but there can be at most one. Cases:
Copy Code code as follows:
Class sometype{
Static SomeType () {}
}
When the JIT compiler compiles a method, it looks at which types the code references. Any type defines a type constructor, and the JIT compiler checks whether the current AppDomain has executed the type constructor, if it is not executed, and returns directly without executing. In a multithreaded environment, there may be multiple execution of the same method at the same time, and the CLR expects that one type constructor in each AppDomain is executed only once, resolving the problem by using a mutex thread to synchronize the lock when calling the type Builder.
Only static fields of type can be accessed in the type constructor, typically only those fields are initialized.
Code inline initialization fields:
Copy Code code as follows:
Class SomeType
{
Static int x = 5;
}
Equivalent to
Copy Code code as follows:
Class SomeType
{
Static int x;
Static SomeType ()
{
x = 5;
}
}
And also:
Copy Code code as follows:
Class SomeType
{
Static int x = 3;
Static SomeType ()
{
x = 5;
}
}
Equivalent to
Copy Code code as follows:
Class SomeType
{
Static int x;
Static SomeType ()
{
x = 3;
x = 5;
}
}
Although C # does not allow the value type to use inline initialization syntax for its instantiated fields, static fields are OK, and the above class can be changed to struct.
The primary reason is that a value type can define a parameterless type constructor, but it is not possible to define a parameterless type instance constructor.