因为在.NET 3.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();
}
}这是从Jon Skeet的博客文章中获得启发的。
因为Nested该类是嵌套的和私有的,所以通过访问Sigleton该类的其他成员(例如,公共的只读属性)不会触发单例实例的实例化。