【问题标题】:Is this a valid, lazy, thread-safe Singleton implementation for C#?这是 C# 的有效、惰性、线程安全的单例实现吗?
【发布时间】:2010-04-11 00:05:28
【问题描述】:

我实现了这样的单例模式:

public sealed class MyClass {

    ...

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

    ...

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

通过谷歌搜索 C# Singleton 实现,这似乎不是在 C# 中做事的常用方法。我找到了一个类似的实现,但是 SingletonHolder 类不是静态的,并且包含一个显式(空)静态构造函数。

这是实现单例模式的有效、惰性、线程安全的方式吗?还是我缺少什么?

【问题讨论】:

    标签: c# multithreading singleton thread-safety


    【解决方案1】:

    Jon Skeet 写了一篇关于在 C# 中实现单例模式的 article

    惰性实现是版本 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();
        }
    }
    

    请特别注意,即使构造函数为空,您也必须显式声明它才能将其设为私有。

    【讨论】:

      猜你喜欢
      • 2021-05-12
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多