如果一个类型没有静态构造函数,则字段初始化器将在使用该类型之前执行——或者在运行时突发奇想的任何时候执行
为什么这个代码:
void Main()
{
"-------start-------".Dump();
Test.EchoAndReturn("Hello");
"-------end-------".Dump();
}
class Test
{
public static string x = EchoAndReturn ("a");
public static string y = EchoAndReturn ("b");
public static string EchoAndReturn (string s)
{
Console.WriteLine (s);
return s;
}
}
产量:
-------start-------
a
b
Hello
-------end-------
而这段代码:
void Main()
{
"-------start-------".Dump();
var test=Test.x;
"-------end-------".Dump();
}
产量
a
b
-------start-------
-------end-------
a
和的顺序b
是可以理解的。但为什么处理 static method
不同于. static field
我的意思是为什么静态方法与静态字段的起始行和结束行位于不同的位置?我的意思是-在这两种情况下,他都必须初始化这些字段……那为什么呢?
(我知道我可以添加静态 ctor 使其相同 - 但我问的是这种特殊情况。)
(ps Dump() 就像 console.write)