C#惰性线程安全的单例(适用于.NET 3.5或更旧版本,替代实现)
示例
因为在.NET3.5及更低版本中,您没有Lazy<T>类,所以使用以下模式:
public class Singleton
{
private Singleton() //阻止公共实例化
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
private class Nested
{
//明确的静态构造函数告诉C#编译器
//不要将类型标记为beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}这是从JonSkeet的博客文章中获得启发的。
因为Nested该类是嵌套的和私有的,所以通过访问Sigleton该类的其他成员(例如,公共的只读属性)不会触发单例实例的实例化。
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短