静态变量声明的顺序

Sam*_*sov -1 c#

我有这两个代码:

private static int a = 5;
private static int b = a;

static void Main(string[] args)
{
    Console.WriteLine(b);
}
Run Code Online (Sandbox Code Playgroud)

private static int b = a;
private static int a = 5;

static void Main(string[] args)
{
    Console.WriteLine(b);
}
Run Code Online (Sandbox Code Playgroud)

请解释为什么在第一种情况下输出为5,但在第二种情况下输出为0

Rom*_*syk 9

在第二种情况下,编译器将为类型生成以下静态构造函数:

static Program()
{
   // Note: this type is marked as 'beforefieldinit'.
   Program.b = Program.a;
   Program.a = 5;
}
Run Code Online (Sandbox Code Playgroud)

所以,当它分配时a等于.然后设置为0ba5