开发者

Singleton in C#

I would like to collect more variants for create singleton class. Could you please provide to me the best creation way in C# by your opinion.

Thanks.

public sealed class Singleton
{
    Singleton _instance = null;

    public Singleton Instance
    {
        get
        {
            if(_instance == null)
       开发者_JAVA技巧         _instance = new Singleton();

            return _instance;
        }
    }

    // Default private constructor so only we can instanctiate
    private Singleton() { }

    // Default private static constructor
    private static Singleton() { }
}


I have an entire article on this which you may find useful.

Oh, and try to avoid using the singleton pattern in general, due to its pain for testability etc :)


look here : http://www.yoda.arachsys.com/csharp/singleton.html

public sealed class Singleton
{
    static readonly Singleton instance=new Singleton();

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

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜