C# Lazy关键字 简介

C# Lazy 简介

暂时没时间写注释,之后会补上(∩_∩)~

上代码,Run一下啦~

		/// 
        /// 程序入口
        /// 
        /// 
         static void Main(string[] args)
        {

            //不使用延迟加载例子
            Stopwatch win7Stopwatch = Stopwatch.StartNew();
            win7Stopwatch.Start();
            Windows7 win7 = new Windows7(1);
            win7Stopwatch.Stop();
            Console.WriteLine($"Windows7 before get value waste time:[{win7Stopwatch.Elapsed}]");

           
            //使用延迟加载例子
            Stopwatch win10Stopwatch = Stopwatch.StartNew();
            win10Stopwatch.Start();
            Windows10 windows10 = new Windows10(1);
            win10Stopwatch.Stop();
            Console.WriteLine($"Windows10.SoftWares is initialized or not:[{windows10.SoftWares.IsValueCreated}]");
            Console.WriteLine($"Windows10 before get value waste time:[{win10Stopwatch.Elapsed}]");
            
            Console.Read();
        }

		/// 
        /// win7电脑开机很慢
        /// 
        public class  Windows7
        {
            public int Id { get; private set; }
            //不使用延迟加载,解除上面注释切换使用延迟加载
            public List SoftWares { get; set; }
            public Windows7(int id)
            {
                this.Id = id;
                //不使用延迟加载,解除上面注释切换使用延迟加载
                SoftWares = SoftWareRepository.GetSoftWaresByID(id);
                Console.WriteLine("Windows7 Initializer");
            }
        }

        /// 
        /// win10电脑开机很快
        /// 
        public class Windows10
        {
            public int Id { get; private set; }
            //使用延迟加载
            public Lazy> SoftWares { get; set; }
            public Windows10(int id)
            {
                this.Id = id;
                //使用延迟加载
                SoftWares = new Lazy>(() => SoftWareRepository.GetSoftWaresByID(id));
                Console.WriteLine("Windows10 Initializer");
            }
        }

        public class SoftWare
        {
            public int Id { get; set; }
            public string Title { get; set; }
        }
        
        public class SoftWareRepository
        {
            public static List GetSoftWaresByID(int blogUserID)
            {
                List softWares = new List();
                for (var i = 0; i < 10000000; i++)
                {
                    softWares.Add(new SoftWare()
                    {
                        Id = i,
                        Title = "Lazytitle"+i
                    });
                }
                return softWares;
            }
        }

你可能感兴趣的:(个人心德,.Net)