下面再用一个例子,演示延迟加载:
在这个例子中,使用了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;
- }
- }
|
|