简体   繁体   English

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

[英]Which is called first static constructor or private constructor

I was reading a tutorial for implementing Singleton and the code is 我正在阅读实现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
        }
    }

When I write Singleton.Instance, the output is 当我写Singleton.Instance时,输出是

Private 私人的
Static 静态的

I was expecting it to be 我期待它

Static 静态的
Private 私人的

Reason being that when I read a MSDN tutorial " https://msdn.microsoft.com/en-us/library/k9x6w0hc.aspx " 原因是当我阅读MSDN教程“ https://msdn.microsoft.com/en-us/library/k9x6w0hc.aspx

I saw that public constructor was called after the static constructor. 我看到在静态构造函数之后调用了公共构造函数。

Why is there a difference? 为什么会有区别?

The static constructor has to complete before code outside the class can use the class. 静态构造函数必须在类之外的代码可以使用该类之前完成。 But the language specification has to allow the instance constructor to complete before the static constructor does, so that you could eg do this: 但是语言规范必须允许实例构造函数在静态构造函数之前完成,这样你就可以这样做:

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

Note that in your example, that's essentially what happens anyway. 请注意,在您的示例中,这基本上是发生的事情。 Field initializers essentially become part of the constructor; 字段初始化器基本上成为构造函数的一部分; they just execute first. 他们只是先执行。

This is corroborated by the generated IL: 这由生成的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         

See also related (but not duplicate) question and Eric Lippert's typically excellent answer here: Calling of Static Constructor and Instance Constructor 另请参阅相关(但不重复)的问题和Eric Lippert在这里的典型答案: 调用静态构造函数和实例构造函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM