Design patterns 在有性能约束的C#中实现单例设计模式的最佳方法是什么?
请告诉我在C#中实现单例设计模式的最佳方法是什么,并带有性能约束?摘自:Design patterns 在有性能约束的C#中实现单例设计模式的最佳方法是什么?,design-patterns,Design Patterns,请告诉我在C#中实现单例设计模式的最佳方法是什么,并带有性能约束?摘自: public class Singleton { static readonly Singleton _instance = new Singleton(); static Singleton() { } private Singleton() { } static public Singleton Instance { get { return _inst
public class Singleton
{
static readonly Singleton _instance = new Singleton();
static Singleton() { }
private Singleton() { }
static public Singleton Instance
{
get { return _instance; }
}
}
在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()
{
}
}
公共密封类单例
{
私有静态只读惰性=
新的懒惰(()=>newsingleton());
公共静态单例实例{get{return lazy.Value;}}
私人单身人士()
{
}
}
它很简单,性能也很好。它还允许您检查是否已使用属性创建了实例(如果需要)。您所说的“性能约束”是什么?我希望实现得最快。我在这个网站上听说过一篇文章,但不记得名字了。如果有人知道,请张贴在这里。