为什么静态变量在 C# 中声明之前就可用

How come static variable is usable even before it is declared in C#

我能够编译并运行以下程序成功:

class MyClass1
{
    public static int x = y;
    public static int y = 10;
}

static void Main(string[] args)
{
    Console.WriteLine(MyClass1.x); //prints 0
    Console.WriteLine(MyClass1.y); //prints 10
}

为什么编译成功? x 是如何在 y 被声明和初始化之前得到它的值的?如果是实例字段,也会出现编译时错误。

它们是按顺序初始化的。首先 x 设置为 y 的值,即 0(默认值)。然后y设置为10.

来自 ECMA-334 - 17.4.5.1 静态字段初始化

The static field variable initializers of a class declaration 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 (§17.11) 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.

因此 y 变量用于 x 变量的初始化行,并使用默认值 0

进行初始化