Reference from http://blog.csdn.net/dql1982/archive/2007/12/04/1916559.aspx
The initial values of static field variables of the class correspond to a sequence of values, which are executed in the order of the text they appear in the relevant class declaration. If a static constructor exists in the class, the execution of the initial value setting item of the static field occurs before the execution of the static constructor. Otherwise, the initial value of the static field is executed before the first time the static field of the class is used, but the actual execution time depends on the specific implementation. In the following example:
Using System;
Class Test
... {
Static Void Main () ... {
Console. writeline ("{0} {1}", B .y, a.x );
}
Public Static Int F ( String S) ... {
Console. writeline (s );
Return 1;
}
}
Class A
... {
Public Static IntX=Test. F ("Init");
}
Class B
... {
Public Static IntY=Test. F ("Init B");
} Or generate the following output: init
Init B
1 or generate the following output: init B
Init
1. This is because X And Y The execution sequence of the initial value setting items cannot be determined in advance, and both of the above two sequences may occur. The only thing that can be determined is that they will certainly occur before those fields are referenced. However, the following example: Using System;
Class Test
... {
Static Void Main () ... {
Console. writeline ("{0} {1}", B .y, a.x );
}
Public Static Int F ( String S) ... {
Console. writeline (s );
Return 1;
}
}
Class A
... {
Static A () ... {}
Public Static Int X = Test. F ( " Init " );
}
Class B
... {
Static B () ... {}
Public Static Int Y = Test. F ( " Init B " );
}
The output must be: init B
Init
1 1
This is because the rule about when to execute a static ConstructorRules:BStatic Constructor(AndBTo set the initial values of static fields.)Must be inABefore the static constructor and field initial value setting.