1. 概述
我们创建某一个对象需要很大的消耗,而这个对象在运行过程中又不一定用到,为了避免每次运行都创建该对象,这时候延迟初始化(也叫延迟实例化)就出场了。
延迟初始化出现于.NET 4.0,主要用于提高性能,避免浪费计算,并减少程序内存要求。也可以称为,按需加载。
2. 基本语法
Lazy<T> xx = new Lazy<T>();//xx代表变量名
3. 举例实现
首先创建一个Student类,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LazyTest
{
class Student
{
public Student()
{
this.Name = "DefaultName";
Console.WriteLine("调用Student的构造函数");
}
public string Name { get; set; }
}
}创建一个控制台程序,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LazyTest
{
class Program
{
static void Main(string[] args)
{
Lazy<Student> student = new Lazy<Student>();
if (!student.IsValueCreated)
{
Console.WriteLine("Student未初始化");
}
Console.WriteLine(student.Value.Name);
if (student.IsValueCreated)
{
Console.WriteLine("Student已经初始化");
}
Console.ReadKey();
}
}
}设置断点调试后发现,在new完之后,student的IsValueCreated的值是false,value的值是null
延迟
初始化
创建
student
对象
lazy
isvaluecreated
c#
代码
程序