C# 单例与延迟加载

//这是一个单例,
//调用:A.Instence().Start()
public sealed class A { private static readonly A instence = null; static A() { instence = new A(); } private A() { //初始化 } public static A Instence() { return instence; } public void Start() { //do something } } //延迟加载
//调用:A.Instance.Start()
//执行到调用代码的时候才会去创建类的实例对象

public sealed class A
{
static readonly Lazy<A> instanceHolder = new Lazy<A>(() => new A());
   A()
  {
    
// 初始化
  }
    public static A Instance => instanceHolder.Value;
    public void Start()
    {
         //do something
    }
}

 

posted @ 2020-07-23 15:06  Vaynedy  阅读(213)  评论(0编辑  收藏  举报