C#中的单身人士

我想为创建单例类收集更多变体。 你能否根据你的意见向我提供C#中最好的创作方式。

谢谢。

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() { } } 

我有一篇关于此的文章 ,您可能会发现它很有用。

哦,并且尽量避免使用单例模式,因为它的可测试性等等:)

看这里: 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; } } }