Joe*_*ank 9 c# static-members static-classes c#-4.0
考虑以下课程:
public class MyClass
{
public static string[] SomeAmazingConsts = { Const1 };
public static string Const1 = "Constant 1";
public static string Const2 = "Constant 2";
}
Run Code Online (Sandbox Code Playgroud)
现在,查看用法:
class Program
{
static void Main(string[] args)
{
string[] s = MyClass.SomeAmazingConsts;
//s[0] == null
}
}
Run Code Online (Sandbox Code Playgroud)
问题是s [0] == null!怎么会发生这种情况?现在,重新排序MyClass的静态变量,如下所示:
public class MyClass
{
public static string Const1 = "Constant 1";
public static string Const2 = "Constant 2";
public static string[] SomeAmazingConsts = { Const1 };
}
Run Code Online (Sandbox Code Playgroud)
事情开始正常运作.任何人都可以对此有所了解吗?
Adr*_*der 14
类的静态字段变量初始值设定项对应于以它们出现在类声明中的文本顺序执行的赋值序列.
因此,初始化从上到下发生,并且在第一种情况下Const1尚未初始化,因此null