懒惰线程安全单例(适用于 .NET 3.5 或更早版本的备用实现)

因为在 .NET 3.5 及更早版本中,你没有 Lazy<T> 类,所以你使用以下模式:

public class Singleton
{
    private Singleton() // prevents public instantiation
    {
    }

    public static Singleton Instance
    {
        get
        {
            return Nested.instance;
        }
    }
    
    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}

这是受 Jon Skeet 博客文章的启发。

因为 Nested 类是嵌套的并且是私有的,所以不会通过访问 Sigleton 类的其他成员(例如,公共只读属性)来触发单例实例的实例化。