c#延迟加载

    public class BlogUser
    {
        public int Id { get; private set; }
        public Lazy<List<Article>> Articles { get; private set; }
        public BlogUser(int id)
        {
            this.Id = id;
            Articles = new Lazy<List<Article>>(() => 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<Article> GetArticesByID(int blogUserID)
        {
            List<Article> articles = new List<Article> {            
                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;
        }
    }

main

          BlogUser blogUser = new BlogUser(1);
            Console.WriteLine("blogUser has been initialized");

            foreach (var article in blogUser.Articles.Value)
            {
                Console.WriteLine(article.Title);
            }  

 

posted @ 2015-07-23 15:20  s_p  阅读(310)  评论(0编辑  收藏  举报