C# 性能优化 --- Lazy<T> 用法学习

参考原文:https://kb.cnblogs.com/page/99182/

延迟实例化,对于需要创建大量对象,而又不需要立即使用的场景非常有用。一下实例说明了Lazy<T>的用法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LazyDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            BlogUser blogUser = new BlogUser(1);
            Console.WriteLine("blogUser has been initialized");
            //使用延迟加载
            //foreach (var article in blogUser.Articles.Value)
            //不使用延迟加载,要做比较将下面注释放开,上面那句注释即可
            foreach (var article in blogUser.Articles)
            {
                Console.WriteLine(article.Title);
            }
            Console.Read();
        }
    }

    public class BlogUser
    {
        public int Id { get; private set; }
        //使用延迟加载
        //public Lazy<List<Article>> Articles { get; set; }
        //不使用延迟加载,要做比较将下面注释放开,上面那句注释即可
        public List<Article> Articles { get; set; }
        public BlogUser(int id)
        {
            this.Id = id;
            //使用延迟加载
            //Articles = new Lazy<List<Article>>(() => ArticleServices.GetArticesByID(id));
            //不使用延迟加载,要做比较将下面注释放开,上面那句注释即可
            Articles = 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;
        }
    }
}

运行结果:

 

posted on 2020-12-01 20:49  积跬步---行千里  阅读(282)  评论(0编辑  收藏  举报