Order of static constructors/initializers in C#

后端 未结 4 1430
梦如初夏
梦如初夏 2020-12-03 10:02

While working on a C# app I just noticed that in several places static initializers have dependencies on each other like this:

static private List         


        
4条回答
  •  离开以前
    2020-12-03 10:53

    See section 10.4 of the C# spec for the rules here:

    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.

    So in other words, in your example 'b' is initialized to its default state (null) and so the reference to it in the initializer of 'a' is legal but would result in a NullReferenceException.

    These rules are different to Java's (see section 8.3.2.3 of the JLS for Java's rules about forward references, which are more restrictive).

提交回复
热议问题