Lazy initialization in .NET 4

前端 未结 3 1005
我寻月下人不归
我寻月下人不归 2021-01-31 17:29

What is lazy initialization. here is the code i got after search google.

class MessageClass
{
    public string Message { get; set; }

    public MessageClass(st         


        
相关标签:
3条回答
  • 2021-01-31 18:12

    Check out msdn documentation over here : Lazy Initialization

    Lazy initialization of an object means that its creation is deferred until it is first used. Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements.

    0 讨论(0)
  • 2021-01-31 18:13

    The purpose of the Lazy feature in .NET 4.0 is to replace a pattern many developers used previously with properties. The "old" way would be something like

    private MyClass _myProperty;
    
    public MyClass MyProperty
    {
        get
        {
            if (_myProperty == null)
            {
                _myProperty = new MyClass();
            }
            return _myProperty;
        }
    }
    

    This way, _myProperty only gets instantiated once and only when it is needed. If it is never needed, it is never instantiated. To do the same thing with Lazy, you might write

    private Lazy<MyClass> _myProperty = new Lazy<MyClass>( () => new MyClass());
    
    public MyClass MyProperty
    {
        get
        {
            return _myProperty.Value;
        }
    }
    

    Of course, you are not restricted to doing things this way with Lazy, but the purpose is to specify how to instantiate a value without actually doing so until it is needed. The calling code does not have to keep track of whether the value has been instantiated; rather, the calling code just uses the Value property. (It is possible to find out whether the value has been instantiated with the IsValueCreated property.)

    0 讨论(0)
  • 2021-01-31 18:13

    "Lazy initialization occurs the first time the Lazy.Value property is accessed or the Lazy.ToString method is called.

    Use an instance of Lazy to defer the creation of a large or resource-intensive object or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program."

    http://msdn.microsoft.com/en-us/library/dd642331.aspx

    0 讨论(0)
提交回复
热议问题