System.Lazy<T>延迟加载
在很多情况下,有些对象需要在使用时加载或根据逻辑动态加载。有些情况如果不延迟加载,可能会影响效率甚至抛出Timeout Exception。如网络操作、数据库操作、文件IO操作
直接上代码,方便我们理解怎么通过Lazy类实现对象的延迟加载。
class Program { static void Main(string[] args) { foreach (var item in Product.GetProductListLazy()) { //下面的操作会执行Product类的构造函数 Product p = item.Value; //构造函数执行完成 int id = item.Value.Id; Console.WriteLine(id); } Console.ReadKey(); } } public class Product { public int Id { set; get;