The static constructor of a class is also called the Type constructor. It is controlled by the CLR at the time of its call:
CLR selects one of the following time to call the static constructor:
1. Before the first instance of the type is created, or before the non-inherited field of the type or the first access by the Member. The "before" here indicates the meaning of the front and back links. The time here is accurate!
2. The time before a non-inherited static field or a member's first visit may vary!
Since the call time is unknown, we 'd better not compile code that depends on the execution sequence of a specific static constructor. This will easily lead to unpredictable consequences!
Let's take a closer look at some interesting behavior of the static constructor by taking a look at three demos:
Demo1:
Static void Main (string [] args)
{
Console. WriteLine (B. strText );
}
Public class
{
Public static string strText;
Static ()
{
StrText = "aaaa ";
}
}
Public class B:
{
Static B ()
{
StrText = "bbbb ";
}
}
You can guess what the result is. Some people may think that the output is bbbb. To access B. strText, you need to call the static constructor static B () of Class B (). In fact, the output result is aaaa. Because strText is A static field of Class A, and Class B only inherits this field, the static constructor static A () of Class A will be called here (), the output result is aaaa. There is nothing to say about this. I believe everyone can see this result.
Let's take a look at the second Demo:
Demo2:
Static void Main (string [] args)
{
B B = new B ();
A a = new ();
Console. WriteLine (B. strText );
}
Public class
{
Public static string strText;
Static ()
{
StrText = "aaaa ";
}
}
Public class B:
{
Static B ()
{
StrText = "bbbb ";
}
}
You can guess what the output result is. Some people may think that aaaa will be output because static B () is called before new B (), and static A needs to be called before new, the result is aaaa, but it is not true. The correct result is bbbb for the following reasons:
Before executing new B ();, the static constructor of Class B will call, that is, it will call:
Static B ()
{
StrText = "bbbb ";
}
When strText = "bbbb" is executed, you need to access the strText field, and the strText field of B is inherited from Class A. Therefore, you need to first call:
Static ()
{
StrText = "aaaa ";
}
After this function is executed, the strText value is aaaa.
Then the code returns to static B (). Then, the strText = "bbbb" line in static B () is executed. Therefore, the value of strText is bbbb.
When A a = new A (); is executed, the static constructor of A is not called because it has already been called, static functions are called only once throughout the lifecycle of the application domain!
Please give me more advice!