[英]Strange behavior on static members of a class - How's this possible?
考虑以下课程:
public class MyClass
{
public static string[] SomeAmazingConsts = { Const1 };
public static string Const1 = "Constant 1";
public static string Const2 = "Constant 2";
}
现在,查看用法:
class Program
{
static void Main(string[] args)
{
string[] s = MyClass.SomeAmazingConsts;
//s[0] == null
}
}
问题是s [0] == null! 怎么会发生这种情况? 现在,重新排序MyClass的静态变量,如下所示:
public class MyClass
{
public static string Const1 = "Constant 1";
public static string Const2 = "Constant 2";
public static string[] SomeAmazingConsts = { Const1 };
}
事情开始正常运作。 任何人都可以对此有所了解吗?
类的静态字段变量初始值设定项对应于以它们出现在类声明中的文本顺序执行的赋值序列。
因此,初始化从上到下发生,并且在第一种情况下, Const1
尚未初始化,因此为null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.