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

Raj*_*jat 9 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
        }
    }
Run Code Online (Sandbox Code Playgroud)

当我写Singleton.Instance时,输出是

私人
静态

我期待它

静态
私人

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

我看到在静态构造函数之后调用了公共构造函数.

为什么会有区别?

Pet*_*iho 5

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

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

请注意,在您的示例中,这基本上是发生的事情.字段初始化器基本上成为构造函数的一部分; 他们只是先执行.

这由生成的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         
Run Code Online (Sandbox Code Playgroud)

另请参阅相关(但不重复)的问题和Eric Lippert在这里的典型答案:调用静态构造函数和实例构造函数