Singleton in C#

此生再无相见时 提交于 2019-12-08 05:06:37

问题


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)
                _instance = new Singleton();

            return _instance;
        }
    }

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

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

回答1:


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 :)




回答2:


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;
        }
    }
}


来源:https://stackoverflow.com/questions/5040986/singleton-in-c-sharp

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