简体   繁体   English

这是C#的有效,惰性,线程安全的Singleton实现吗?

[英]Is this a valid, lazy, thread-safe Singleton implementation for C#?

I implemented a Singleton pattern like this: 我实现了一个Singleton模式,如下所示:

public sealed class MyClass {

    ...

    public static MyClass Instance {
        get { return SingletonHolder.instance; }
    }

    ...

    static class SingletonHolder {
        public static MyClass instance = new MyClass ();
    }
}

From Googling around for C# Singleton implementations, it doesn't seem like this is a common way to do things in C#. 从C#Singleton实现的Googling来看,这似乎并不是在C#中执行事务的常用方法。 I found one similar implementation, but the SingletonHolder class wasn't static, and included an explicit (empty) static constructor. 我找到了一个类似的实现,但是SingletonHolder类不是静态的,并且包含一个显式(空)静态构造函数。

Is this a valid, lazy, thread-safe way to implement the Singleton pattern? 这是实现Singleton模式的有效,懒惰,线程安全的方法吗? Or is there something I'm missing? 还是我想念的东西?

Jon Skeet has written an article about implementing the Singleton pattern in C#. 乔恩·斯凯特(Jon Skeet)撰写了一篇有关在C#中实现Singleton模式的文章

The lazy implementation is version 5: 懒惰的实现是版本5:

public sealed class Singleton
{
    Singleton()
    {
    }

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

    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}

Notice in particular that you have to explicitly declare a constructor even if it is empty in order to make it private. 特别要注意的是,即使要使构造函数为空,也必须显式声明它。

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

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