今天有人问我一道面试题
class
Class1
... {
public static int i = GetNum();
private static int num=1;
public static int GetNum()
...{
return num;
}
public int j = GetNum();
}
... {
public static int i = GetNum();
private static int num=1;
public static int GetNum()
...{
return num;
}
public int j = GetNum();
}
Console.WriteLine(Class1.i);的结果为0
Console.WriteLine(new Class1().j);的结果为1
class
Class1
... {
private static int num=1;
public static int i = GetNum();
public static int GetNum()
...{
return num;
}
public int j = GetNum();
}
... {
private static int num=1;
public static int i = GetNum();
public static int GetNum()
...{
return num;
}
public int j = GetNum();
}
Console.WriteLine(Class1.i);的结果为1
Console.WriteLine(new Class1().j);的结果为1
从msdn上查到“静态成员在第一次被访问之前并且在任何静态构造函数(如调用的话)之前初始化”,但没说明初始化顺序,根据调试分析,得出结论静态变量是从上到下进行初始化的。