延迟初始化,直到被使用才创建该对象,主要用于性能优化。
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