gpt4 book ai didi

c# - C# 中静态构造函数/初始化器的顺序

转载 作者:IT王子 更新时间:2023-10-29 04:42:43 26 4
gpt4 key购买 nike

在开发 C# 应用程序时,我注意到在几个地方静态初始化程序相互依赖,如下所示:

static private List<int> a = new List<int>() { 0 };
static private List<int> b = new List<int>() { a[0] };

没有做任何特别的工作。那只是运气吗? C# 是否有解决此问题的规则?

编辑:(回复:Panos)在文件中词法顺序似乎为王?跨文件呢?

在寻找过程中,我尝试了这样的循环依赖:

static private List<int> a = new List<int>() { b[0] };
static private List<int> b = new List<int>() { a[0] };

并且程序运行不一样(测试服全面失败,我没有进一步查看)。

最佳答案

参见 section 10.4 of the C# spec这里的规则:

when a class is initialized, all static fields in that class are first initialized to their default values, and then the static field initializers are executed in textual order. Likewise, when an instance of a class is created, all instance fields in that instance are first initialized to their default values, and then the instance field initializers are executed in textual order. It is possible for static fields with variable initializers to be observed in their default value state. However, this is strongly discouraged as a matter of style.

换句话说,在您的示例中,“b”被初始化为其默认状态(null),因此在“a”的初始化程序中对它的引用是合法的,但会导致 NullReferenceException。

这些规则与 Java 的不同(请参阅 section 8.3.2.3 of the JLS 以了解 Java 关于前向引用的规则,这些规则更具限制性)。

关于c# - C# 中静态构造函数/初始化器的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/185384/

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