gpt4 book ai didi

c# - 为什么静态字段初始化发生在静态构造函数之前?

转载 作者:可可西里 更新时间:2023-11-01 08:21:03 24 4
gpt4 key购买 nike

以下代码:

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之前?

最佳答案

ctor 位于字段初始值设定项之后的原因是因为这是指定的方式。来自 C# 规范(重点是我的):

10.5.5.1 Static field initialization The static field variable initializers of a class 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 (§10.12) 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

如果您想完全控制初始化顺序,请将其全部移到构造函数中。

关于c# - 为什么静态字段初始化发生在静态构造函数之前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8285168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com