I just used the static constructor in the static class, but I don't know much about it. So I went to Google and read someArticle, Send some of your summary.
Google's original intention is:
Is the initialization of members in the class directly initialized or initialized in the static constructor of the class?
Let's show the final suggestions first:
The first is a simple static member, such as a value type, which is completed using the member initialization statement;
The initialization of the second static member is complex, or an exception may occur. You can use the static constructor to complete the initialization.
The following is an example on the Internet. It is mainly used to familiarize yourself with the execution sequence of static constructor:
Static Class A
{
Public Static Int X = B .y;
Static A ()
{
++ X;
}
}
Static Class B
{
Public Static Int Y = a.x;
Static B ()
{
++ Y;
}
}
Class Program
{
Static Void Main ( String [] ARGs)
{
Console. writeline (a.x );
Console. writeline (B .y );
Console. Read ();
}
}
Do not close the ticket. Let's talk about the execution result first.
2
1
Run console first. writeline (a.x), so it will jump to Class A. Because the member X is called, allocate space for X and initialize it to 0, then execute the statement "x = B .y" and jump to Class B during execution. First, initialize the member "Y" and initialize it to "0". Continue to execute the statement "Y = a.x, because a.x has been initialized to 0, so directly y = 0, and then execute the static constructor of Class B, so y becomes 1, after execution, return to the sentence x = B .y, and assume that B .y = 1, so x = 1, and then execute the static constructor of Class A, so a.x = 2.
There may be some bypasses above. In fact, the execution sequence is: Initialize the static members in the class first, and then execute the static constructor of the class. The execution sequence is: static members of the class> static constructor of the class.
First, I have some understanding of the static constructor.