Static constructor can run after the non-static constructor. Is this a compiler bug?

后端 未结 4 482
轮回少年
轮回少年 2020-12-01 21:53

The output from the following program is:

Non-Static
Static
Non-Static

Is this a compiler bug? I

4条回答
  •  感动是毒
    2020-12-01 22:06

    See ECMA 334 §17.4.5.1:

    17.4.5.1 Static field initialization

    The static field variable initializers of a class declaration 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 (§17.11) 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

    Specifically: "execution of the static field initializers occurs immediately prior to executing that static constructor".

    Your static MyClass aVar must be initialized before your static constructor executes (or, at least, it must appear that way). Without that static member, the static constructor should be called before any non-static constructors.

    If you still want a MyClass singleton, you can put it in a container class and refer to it using that, e.g.:

    public static class MyClassSingleton
    {
        public static MyClass aVar = new MyClass();
    }
    

提交回复
热议问题