Why static fields initialization occurs before the static constructor?

后端 未结 1 809
醉话见心
醉话见心 2020-12-04 01:39

The following code:

static void Main(string[] args)
{
    Console.WriteLine(\"0\");
    string h = Foo.X;
    Console.WriteLine(\"2\");
}

public static cla         


        
相关标签:
1条回答
  • 2020-12-04 01:56

    The reason ctor is after the field initializers is because that's the way it is specified. From the C# specification (emphasis is mine):

    10.5.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. If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class

    If you want to have total control of your initialization order, move it all inside the constructor.

    0 讨论(0)
提交回复
热议问题