C# Lazy 简介
暂时没时间写注释,之后会补上(∩_∩)~
上代码,Run一下啦~
/// <summary>
/// 程序入口
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//不使用延迟加载例子
Stopwatch win7Stopwatch = Stopwatch.StartNew();
win7Stopwatch.Start();
Windows7 win7 = new Windows7(1);
win7Stopwatch.Stop();
Console.WriteLine($"Windows7 before get value waste time:[{win7Stopwatch.Elapsed}]");
//使用延迟加载例子
Stopwatch win10Stopwatch = Stopwatch.StartNew();
win10Stopwatch.Start();
Windows10 windows10 = new Windows10(1);
win10Stopwatch.Stop();
Console.WriteLine($"Windows10.SoftWares is initialized or not:[{windows10.SoftWares.IsValueCreated}]");
Console.WriteLine($"Windows10 before get value waste time:[{win10Stopwatch.Elapsed}]");
Console.Read();
}
/// <summary>
/// win7电脑开机很慢
/// </summary>
public class Windows7
{
public int Id { get; private set; }
//不使用延迟加载,解除上面注释切换使用延迟加载
public List<SoftWare> SoftWares { get; set; }
public Windows7(int id)
{
this.Id = id;
//不使用延迟加载,解除上面注释切换使用延迟加载
SoftWares = SoftWareRepository.GetSoftWaresByID(id);
Console.WriteLine("Windows7 Initializer");
}
}
/// <summary>
/// win10电脑开机很快
/// </summary>
public class Windows10
{
public int Id { get; private set; }
//使用延迟加载
public Lazy<List<SoftWare>> SoftWares { get; set; }
public Windows10(int id)
{
this.Id = id;
//使用延迟加载
SoftWares = new Lazy<List<SoftWare>>(() => SoftWareRepository.GetSoftWaresByID(id));
Console.WriteLine("Windows10 Initializer");
}
}
public class SoftWare
{
public int Id { get; set; }
public string Title { get; set; }
}
public class SoftWareRepository
{
public static List<SoftWare> GetSoftWaresByID(int blogUserID)
{
List<SoftWare> softWares = new List<SoftWare>();
for (var i = 0; i < 10000000; i++)
{
softWares.Add(new SoftWare()
{
Id = i,
Title = "Lazytitle"+i
});
}
return softWares;
}
}