问题描述
请让我知道在C#中使用性能约束的C#中实现单身设计模式的最佳方法?
推荐答案
从 c#in Depth : 从C#中实现单例模式的方式有多种,从 不适用于完全懒惰的,线程安全性,简单且性能高的版本.
最佳版本 - 使用.net 4的懒惰类型:
public sealed class Singleton { private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton()); public static Singleton Instance { get { return lazy.Value; } } private Singleton() { } }
它很简单,而且表现良好.它还允许您检查是否已经使用 Isvaluecreated <<属性,如果您需要.
其他推荐答案
public class Singleton { static readonly Singleton _instance = new Singleton(); static Singleton() { } private Singleton() { } static public Singleton Instance { get { return _instance; } } }
问题描述
Please let me know what the best way to implement Singleton Design Pattern in C# with performance constraint?
推荐答案
Paraphrased from C# in Depth: There are various different ways of implementing the singleton pattern in C#, from Not thread-safe to a fully lazily-loaded, thread-safe, simple and highly performant version.
Best version - using .NET 4's Lazy type:
public sealed class Singleton { private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton()); public static Singleton Instance { get { return lazy.Value; } } private Singleton() { } }
It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.
其他推荐答案
public class Singleton { static readonly Singleton _instance = new Singleton(); static Singleton() { } private Singleton() { } static public Singleton Instance { get { return _instance; } } }