单个 C# 中的静态成员初始化顺序 class

Static member initialization order within a single C# class

考虑以下带有两个静态成员变量的 class 片段:

            public static class Foo
            {

                static string A = GetA(B);
                static string B = "required for A";
                ...

现在,我的理解是AB会在第一次访问时被初始化。但是,当我执行上面代码片段的完全实现版本时,在初始化 B 之前访问了 A,这导致 null 被传递给 GetA() 而不是"required for A"。为什么不是开始初始化A的行为,然后,当意识到需要B初始化A时,初始化B,然后return完成初始化A?

这方面的一般规则是什么?为什么会这样?我已经看到其他涉及此问题的问题(When do static variables get initialized in C#?) but they don't answer this question exactly. What is the static variable initialization order in C#? 主要讨论它是如何工作的跨越 classes,而不是在单个 class 中(尽管 Jon Skeet 对他的回答的附录——"By popular demand, here was my original answer when I thought the question was about the initialization order of static variables within a class:...." 确实回答了这个问题,但它隐藏在一个更长的答案中。

简而言之,不要这样做。

Standard ECMA-334 C# Language Specification

15.5.6.2 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 (§15.5.6.1). Within a partial class, the meaning of "textual order" is specified by §15.5.6.1. If a static constructor (§15.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

解决方法是:

  • 按顺序使用静态构造函数,
  • 或者只是 Initialise 它们在 Static Constructor 中反过来让你能够控制初始化的顺序(给定上述信息).

我个人建议在 Static ConstructorInitialise 它们,这似乎使它更具体和易于理解,并且不太可能在重构中受到冲击