C # Type constructor

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.