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

老子叫甜甜 提交于 2019-12-12 08:09:33

问题


I implemented a Singleton pattern like this:

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#. I found one similar implementation, but the SingletonHolder class wasn't static, and included an explicit (empty) static constructor.

Is this a valid, lazy, thread-safe way to implement the Singleton pattern? Or is there something I'm missing?


回答1:


Jon Skeet has written an article about implementing the Singleton pattern in C#.

The lazy implementation is version 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.



来源:https://stackoverflow.com/questions/2615527/is-this-a-valid-lazy-thread-safe-singleton-implementation-for-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!