延迟初始化出现于.NET 4.0,主要用于提高性能,避免浪费计算,并减少程序内存要求。也可以称为,按需加载。
基本语法:
Lazy<T> xx = new Lazy<T>();//xx代表变量名
举例实现:
首先创建一个Student类,代码如下:
using System; namespace LazyTest { class Student { public Student() { this.Name = "DefaultName"; Console.WriteLine("调用Student的构造函数"); } public Student(string Name) { this.Name = Name; Console.WriteLine("调用Student(string Name)的构造函数"); } public string Name { get; set; } } }