延迟初始化

public sealed class Singleton
{
Singleton()
{
}

public static Singleton Instance
{
get
{
return Nested.instance;
}
}

class Nested
{
static Nested()
{
}

internal static readonly Singleton instance = new Singleton();
}
}
这是C#单例模式中“延迟初始化”的代码,延迟初始化就是在用到的时候才加载对象实例化,这里也可以声明为静态对象,比如:
public sealed class Singleton
{
Singleton()
{

}

public readonly static Singleton = new Singleton();
}
    这样的话,程序启动的时候,就会先执行对象实例化代码,但如果构造函数请求其他静态对象,而其他的静态对象没有实例化,这样的话就造成对象没有实例话的错误。
    另外对象的延迟初始化,还可以加快程序的启动速度,而需要用到的对象只在被调用到的时候才加载和实例化。
原文地址:https://www.cnblogs.com/brightsea/p/2039866.html