當物件建構成本高昂(如大量運算、資料庫存取、檔案 I/O),但程式執行流程不一定會用到該物件時,延遲載入 可避免不必要的資源浪費。.NET Framework 4.0 引入的 System.Lazy<T> 提供了執行緒安全、簡潔的內建解決方案。
public class Product
{
public Product()
{
// 模擬耗時初始化(如載入大量資料、複雜運算)
System.Threading.Thread.Sleep(1000);
}
public int Id { get; set; }
public string Name { get; set; }
public string TypeCode { get; set; }
}
public class LazyLoadingDemo
{
// 一般建構:呼叫時立即執行建構子
public Product GetProduct(int id, string name, string typeCode)
{
return new Product { Id = id, Name = name, TypeCode = typeCode };
}
// 延遲建構:回傳 Lazy<Product>,直到存取 Value 才真正建構
public Lazy<Product> GetLazyProduct(int id, string name, string typeCode)
{
return new Lazy<Product>(() => new Product
{
Id = id,
Name = name,
TypeCode = typeCode
});
}
}
var demo = new LazyLoadingDemo();
// 1. 立即建構:此行執行完,Product 建構子已跑完(耗時 1 秒)
var p1 = demo.GetProduct(1, "tablet", "x101");
// 2. 延遲建構:此行極快,僅建立 Lazy 代理物件
var p2 = demo.GetLazyProduct(2, "computer", "y202");
// 3. 真正使用時才觸發建構
Console.WriteLine(p1.Name); // 直接讀取,已就緒
Console.WriteLine(p2.Value.Name); // 這裡才真正執行 Product() 建構子
Lazy<T> 預設為 LazyThreadSafetyMode.ExecutionAndPublication,確保多執行緒環境下只會建構一次。可透過建構子參數調整。Value 存取時會重新拋出;後續再次存取仍會拋出同一例外(快取失敗結果)。Lazy<T> 不支援重設;若需重新初始化,請建立新的 Lazy<T> 執行個體。原文連結:https://www.bianceng.cn/Programming/csharp/201410/45753.htm