以下代码:
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");
}
}
将会打印:
0
_aaa
ctor
2
我了解beforefieldinit
的行为(包括是否有静态构造函数等)。
我不理解的是为什么ctor
(在输出中)在_aaa
之后?这毫无意义,如果我想在构造函数中初始化变量怎么办?
问题:
为什么X
的初始化在ctor
之前?
class Foo { public string X = "A"; public Foo() { X = "B"; } }
如果你执行(new Foo()).X
,你会得到"B"
而不是"A"
,因为“B”的赋值发生在后面(覆盖了第一个值)。 - Jeppe Stig Nielsen