静态构造函数可以在非静态构造函数之后运行。这是编译器错误吗? [英] Static constructor can run after the non-static constructor. Is this a compiler bug?

查看:99
本文介绍了静态构造函数可以在非静态构造函数之后运行。这是编译器错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序的输出为:

Non-Static
Static
Non-Static

这是编译器错误吗?我期望:

Is this a compiler bug? I expected:

Static
Non-Static
Non-Static

因为我认为静态构造函数总是在非静态构造函数之前调用。

because I thought the static constructor was ALWAYS called before the non-static constructor.

我使用.net 3.5和.net 4.0在Visual Studio 2010中对此进行了测试。

I tested this with Visual Studio 2010 using both .net 3.5 and .net 4.0.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StaticConstructorBug
{
    class Program
    {
        static void Main(string[] args)
        {
            var mc = new MyClass();

            Console.ReadKey();
        }
    }

    public class MyClass
    {
        public MyClass()
        {
            Console.WriteLine("Non-static");
        }

        static MyClass()
        {
            Console.WriteLine("Static");
        }

        public static MyClass aVar = new MyClass();
    }
}


推荐答案

请参阅 ECMA 334 §17.4.5.1:

See ECMA 334 §17.4.5.1:


17.4.5.1静态字段初始化

17.4.5.1 Static field initialization

类声明的静态字段变量初始化器
对应于
的赋值序列,这些赋值序列按文本顺序执行$ ​​b $ b,其中
出现在类声明中。
如果类中存在静态构造函数(第17.11节)
,则在立即执行该
静态构造函数之前,将执行
静态字段初始化程序。否则,将在第一次使用该类的静态
字段之前,在与实现相关的时间
执行
静态字段初始化程序

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".

您的在静态构造函数执行之前,必须先初始化 static MyClass aVar (或者至少必须以这种方式出现)。如果没有该静态成员,则应在所有非静态构造函数之前调用静态构造函数。

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.

如果您仍然需要 MyClass 单例,您可以将其放在容器类中并使用它来引用它,例如:

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();
}

这篇关于静态构造函数可以在非静态构造函数之后运行。这是编译器错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆