System.Lazy

作者:追风剑情 发布于:2023-2-15 15:18 分类:C#

提供对延迟初始化的支持。

//不会执行new Test()
Lazy<Test> lazyTest = new Lazy<Test>(()=>new Test());
//当调用lazyTest.Value时,才会创建Test对象
lazyTest.Value.Fun();  

示例:延迟创建单例实例

using System;
using System.Threading;

public class SingletonLazy
{
    //延迟创建单例实例
    private static Lazy<SingletonLazy> _instance = new Lazy<SingletonLazy>(LazyThreadSafetyMode.ExecutionAndPublication);

    public static SingletonLazy GetInstance()
    {
        return _instance.Value;
    }
}  

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号