问题描述
以下代码:
static void Main(string[] args){Console.WriteLine("0");字符串 h = Foo.X;Console.WriteLine("2");}公共静态类 Foo{公共静态字符串 X = ((Func)delegate(string g){Console.WriteLine(g);返回 (g);})("_aaa");静态 Foo(){Console.WriteLine("ctor");}}
将打印:
0_aaa演员2我了解 beforefieldinit
行为(有/没有静态构造函数等).
我不理解的是为什么ctor
(在输出中)是after _aaa
?
没有任何意义,如果我想在构造函数中初始化变量怎么办?
问题
为什么X
的初始化在ctor
之前?
ctor
在字段初始值设定项之后的原因是因为这是指定的方式.来自 C# 规范(重点是我的):
10.5.5.1 静态字段初始化类的静态字段变量初始化器对应于一系列赋值按照它们在类中出现的文本顺序执行宣言.如果类中存在静态构造函数(第 10.12 节),静态字段初始值设定项的执行发生在紧接在执行那个静态构造函数.否则,静态字段初始化器在依赖于实现的时间执行第一次使用该类的静态字段
如果您想完全控制初始化顺序,请将其全部移到构造函数中.
The following code:
static void Main(string[] args)
{
Console.WriteLine("0");
string h = Foo.X;
Console.WriteLine("2");
}
public static class Foo
{
public static string X = ((Func<string, string>)delegate(string g)
{
Console.WriteLine(g);
return (g);
})("_aaa");
static Foo()
{
Console.WriteLine("ctor");
}
}
Will print:
0
_aaa
ctor
2
I know about the beforefieldinit
behavior (with/without static constructor etc.).
The thing which I don't understand is why the ctor
(in the output) is after _aaa
?
It doesn't make any sense, what if I want to initialize variables in the constructor?
Question
Why does the initialization of X
is before the ctor
?
The reason ctor
is after the field initializers is because that's the way it is specified. From the C# specification (emphasis is mine):
If you want to have total control of your initialization order, move it all inside the constructor.
这篇关于为什么静态字段初始化发生在静态构造函数之前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!