문제

Consider the following class:

public class MyClass
{
    public static string[] SomeAmazingConsts = { Const1 };
    public static string Const1 = "Constant 1";
    public static string Const2 = "Constant 2";
}

Now, check out the usage:

class Program
{
    static void Main(string[] args)
    {
        string[] s = MyClass.SomeAmazingConsts;
        //s[0] == null
    }
}

The problem is that s[0] == null! How the heck does this happen? Now, reorder the static variable of MyClass as follows:

public class MyClass
{
    public static string Const1 = "Constant 1";
    public static string Const2 = "Constant 2";
    public static string[] SomeAmazingConsts = { Const1 };
}

Things start to work properly. Anyone can shed some light on this?

도움이 되었습니까?

해결책

From 10.4.5.1 Static field initialization

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration.

So the initialization happens top to bottom, and in the first case Const1 has not been initialized, hence the null

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top