Framework4.0提供了一個包裝類 Lazy,可以輕松的實現延遲加載。
-
-
-
-
- Lazystring> s = new Lazystring>(TestLazy.GetString);
|
本例中TestLazy.GetString()方法如下示:
- public class TestLazy
- {
- public static string GetString()
- {
- return DateTime.Now.ToLongTimeString();
- }
- }
|
可以通過IsValueCreated屬性來確定對象是否已創建,通過Value屬性來獲取當前對象的值。
- Console.WriteLine(s.IsValueCreated);
- Console.WriteLine(s.IsValueCreated);
|
下面經出完整代碼,以供測試:
- class Program
- {
- static void Main(string[] args)
- {
-
-
-
-
- Lazy s = new Lazy(TestLazy.GetString);
- Console.WriteLine(s.IsValueCreated);
- Console.WriteLine(s.IsValueCreated);
- }
- }
- public class TestLazy
- {
- public static string GetString()
- {
- return DateTime.Now.ToLongTimeString();
- }
- }
|
下面再用一個例子,演示延遲加載:
在這個例子中,使用了BlogUser對象,該對象包含多個Article對象,當加載BlogUser對象時,Article對象并不加載,當需要使用Article對象時,才加載。
- class Program
- {
- static void Main(string[] args)
- {
- BlogUser blogUser = new BlogUser(1);
- Console.WriteLine("blogUser has been initialized");
- {
- Console.WriteLine(article.Title);}
- }
- }
- public class BlogUser
- {
- public int Id { get; private set; }
- public Lazy> Articles { get; private set; }
- public BlogUser(int id)
- {
- this.Id = id;
- Articles =new Lazy>(()=>ArticleServices.GetArticesByID(id));
- Console.WriteLine("BlogUser Initializer");
- }
- }
- public class Article
- {
- public int Id { get; set; }
- public string Title{get;set;}
- public DateTime PublishDate { get; set;}
- public class ArticleServices
- {
- public static List GetArticesByID(int blogUserID)
- {
- List articles = new List {
- new Article{Id=1,Title="Lazy Load",PublishDate=DateTime.Parse("2011-4-20")},
- new Article{Id=2,Title="Delegate",PublishDate=DateTime.Parse("2011-4-21")},
- new Article{Id=3,Title="Event",PublishDate=DateTime.Parse("2011-4-22")},
- new Article{Id=4,Title="Thread",PublishDate=DateTime.Parse("2011-4-23}
- };
- Console.WriteLine("Article Initalizer");
- return articles;
- }
- }
|
運行結果如圖示:

最后說一下,延遲加載主要應用場景:
當創建一個對象的子對象開銷比較大時,而且有可能在程序中用不到這個子對象,那么可以考慮用延遲加載的方式來創建子對象。另外一種情況就是當程序一啟動時,需要創建多個對象,但僅有幾個對象需要立即使用,這樣就可以將一些不必要的初始化工作延遲到使用時,這樣可以非常有效的提高程序的啟動速度。
這種技術在ORM框架得到了廣泛應用,也并非C#獨有的,比如Java里的Hibernate框架也使用了這一技術。