What is lazy initialization and why is it useful?

前端 未结 9 1167
小鲜肉
小鲜肉 2020-12-12 12:40

What is lazy initialization of objects? How do you do that and what are the advantages?

9条回答
  •  春和景丽
    2020-12-12 12:54

    //Lazy instantiation delays certain tasks. 
    //It typically improves the startup time of a C# application.
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace LazyLoad
    {
        class Program
        {
            static void Main(string[] args)
            {
                Lazy MyLazyClass = new Lazy(); // create lazy class
                Console.WriteLine("IsValueCreated = {0}",MyLazyClass.IsValueCreated); // print value to check if initialization is over
    
                MyClass sample = MyLazyClass.Value; // real value Creation Time
                Console.WriteLine("Length = {0}", sample.Length); // print array length
    
                Console.WriteLine("IsValueCreated = {0}", MyLazyClass.IsValueCreated); // print value to check if initialization is over
                Console.ReadLine();
            }
        }
    
        class MyClass
        {
            int[] array;
            public MyClass()
            {
                array = new int[10];
    
            }
    
            public int Length
            {
                get
                {
                    return this.array.Length;
                }
            }
        }
    }
    
    
    // out put
    
    // IsValueCreated = False
    // Length = 10
    // IsValueCreated = True
    

提交回复
热议问题