这称为第一个静态构造函数或私有构造函数

时间:2017-02-14 05:29:58

标签: c#

我正在阅读实施Singleton的教程,代码是

public class Singleton
    {
        private static readonly Singleton instance = new Singleton();

        static Singleton()
        {
            Console.WriteLine("Static");
        }
        private Singleton()
        {
            Console.WriteLine("Private");
        }

        public static Singleton Instance { get { return instance; } }

        public void DoSomething() {
            //this must be thread safe
        }
    }

当我编写Singleton.Instance时,输出为

  

私人
  静态

我原以为

  

静态
  私人

原因是当我阅读MSDN教程" https://msdn.microsoft.com/en-us/library/k9x6w0hc.aspx"

我看到公共构造函数是在静态构造函数之后调用的。

为什么会有区别?

1 个答案:

答案 0 :(得分:5)

静态构造函数必须在类之外的代码可以使用该类之前完成。但是语言规范必须允许实例构造函数在静态构造函数之前完成,这样你就可以这样做:

static Singleton()
{
    instance = new Singleton();
    // It has to be legal to use "instance" here
    Console.WriteLine("Static");
}

请注意,在您的示例中,无论如何,这基本上都会发生。字段初始化器基本上成为构造函数的一部分;他们只是先执行。

这由生成的IL证实:

// Static constructor
Singleton..cctor:
IL_0000:  newobj      Singleton..ctor     //Calls private constructor first
IL_0005:  stsfld      Singleton.instance  //to create .instance
IL_000A:  nop         
IL_000B:  ldstr       "Static"
IL_0010:  call        System.Console.WriteLine
IL_0015:  nop         
IL_0016:  ret         

另见相关(但不重复)的问题和Eric Lippert在这里的典型答案:Calling of Static Constructor and Instance Constructor