Today I saw a C # pen question about static fields and static constructor initialization. Static functions are a new feature of C #. If you do not know the initialization sequence, you will be confused about this question. For static constructors, see http://www.cnblogs.com/michaelxu/archive/2007/03/29/693401.html. Analyze the initialization sequence of the static constructor from this question.
1 class A <br/> 2 {<br/> 3 Public static int X; <br/> 4 static () <br/> 5 {<br/> 6 x = B .y + 1; <br/> 7} <br/> 8} <br/> 9 class B <br/> 10 {<br/> 11 public static int y = a.x + 1; <br/> 12 static B () {}< br/> 13 static void main () <br/> 14 {<br/> 15 console. writeline ("x = {0}, y = {1}", a.x, B .y); <br/> 16} <br/> 17} <br/>
What is the output result?
1. Call the main function first. It is the static method of B. When any static member of a class is called for the first time, the static constructor is called, before that, you need to allocate memory for the static field y in B and execute the code 11th lines.
2. When the first step of execution calls the static member X of A, it triggers the call of the static constructor of A. When the code is executed in line 6th, the static field y of B appears again in this line, because y has not been initialized, the default value is 0, so this row x = 1
3. After running the static constructor A, return to row 11th, and y = 2.
4. After running the static constructor B, return to main and execute line 4 of the Code to print a.x and B .y. The result is unknown.