Lazy initialization in .NET 4

2019-03-09 19:18发布

问题:

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

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

    public MessageClass(string message)
    {
        this.Message = message;
        Console.WriteLine("  ***  MessageClass constructed [{0}]", message);
    }
}

Lazy<MessageClass> someInstance = new Lazy<MessageClass>(
    () => new MessageClass("The message")
    );

why should i create object in this way....when actually we need to create object in this way......looking for answer.

回答1:

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.)



回答2:

"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



回答3:

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.