Using System;
Namespace Param
{
Class Class1
{
Static int I = getNum ();
Int j = getNum ();
Static int num = 1;
Static int getNum ()
{
Return num;
}
[STAThread]
Static void Main (string [] args)
{
Console. WriteLine (string. Format ("I = {0}", I ));
Console. WriteLine (string. Format ("j = {0}", new Class1 (). j ));
Console. Read ();
}
}
}
The above code was told by a netizen. Let me see the result. I immediately said that the result is
I = 1
J = 1
The result is
I = 0
J = 1
I was shocked and read the code carefully. I was really wrong.
Next I will explain why it is the last result.
For a class, static variables are irrelevant to objects. When will they be initialized? That is, when the first reference is made. When the class generates an object, it can be simply divided into three steps.
1. allocate memory for all static variables. The value in the memory is the default value of the variable type. For the default values of different value types, you can check the relevant information. Note that the value type and reference type are different.
2. assign values to static variables. Pay attention that the value type and reference type are different.
3. Generate the object and call the constructor. First, call the constructor of the parent class of the class, then call the constructor of the class itself to generate the object.
Analyze the above Code:
Console. writeLine (string. format ("I = {0}", I); here I is the static variable, and class class1 is used for the first time. Follow the three steps described above, first, allocate memory for all static variables in class1. Despite the hyperthread technology, the logic of commands is still executed one by one in order. Therefore, the memory is allocated for static int I and the default value of int is 0 in the memory, then allocate memory for the static int num variable. The value is also 0.
Then execute the second step and assign values to the variable: assign values to the static int I variable first, And I = getNum (). Check the code in getNum, that is, return num. At this time, the value of num is 0, so I is 0. Then assign the value to the variable num, num = 1; after this line of code is executed, num is 1. After the analysis, I will not continue to analyze the results. You can easily see what the results are.
People who are a little familiar with c # will certainly not make mistakes as long as they carefully read the code. However, if they take the exam, I believe many people will do wrong. I think this problem is not a technical problem, so it is placed in a non-technical area. In this case, we want to explain that even if we are very familiar with and very basic things during programming, we should take it seriously. Of course, if my employees write such code, it will certainly be criticized by me during code inspection. In fact, the static value type variables are not directly assigned values, but the method to assign values is not commonly used or a bit bt, but I still admire the question.