当前位置: 首页 > 工具软件 > Lazy > 使用案例 >

c# Lazy 的使用

史飞尘
2023-12-01

c# Lazy 的使用


主要作用

延迟初始化,直到被使用才创建该对象,主要用于性能优化。

示例

 class Program
    {
        private static Lazy<Student> _student = new Lazy<Student>();
        static void Main(string[] args)
        {
            if (!_student.IsValueCreated)
            {
                Console.WriteLine("Student 尚未实例化!");
            }
            _student.Value.Name = "张三";
            if (_student.IsValueCreated)
            {
                Console.WriteLine(_student.Value.Name);
            }
        }


    }

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public DateTime Birthday { get; set; }
    }

参考

详见 https://docs.microsoft.com/zh-cn/dotnet/framework/performance/lazy-initialization

 类似资料: