一般用法
public sealed class Singleton
{
private static readonly Singleton _instance = new Singleton();
static Singleton() { }
private Singleton() { }
public static Singleton Instance
{
get { return _instance; }
}
}
例外1:需要在不触发初始化的情况下调用其他静态方法;
例外2:需要知道是否已经实例化了。
内部类
/// <summary>
/// 内部类,完全延迟实例化
/// </summary>
public sealed class Singleton2
{
private Singleton2() { }
public static Singleton2 Instance { get { return Nested._instance; } }
private class Nested
{
static Nested() { }
internal static readonly Singleton2 _instance = new Singleton2();
}
}
.NET 4 (or higher)
/// <summary>
/// 推荐使用单例
/// </summary>
public sealed class Singleton3
{
private static readonly Lazy<Singleton3> _lazy =
new Lazy<Singleton3>(() => new Singleton3());
private Singleton3() { }
public static Singleton3 Instance { get { return _lazy.Value; } }
}