.NET 4中的延迟初始化 [英] Lazy initialization in .NET 4

查看:79
本文介绍了.NET 4中的延迟初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是延迟初始化。这是我在搜索Google之后获得的代码。

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.

推荐答案

Lazy 功能是用属性替换许多以前使用的开发人员的模式。 旧方式类似于

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;
    }
}

这样, _myProperty 仅在需要时实例化一次。如果永远不需要它,则永远不会实例化。要对 Lazy 做同样的事情,您可以写

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;
    }
}

当然,您不限于这样做 Lazy 的方式,但目的是指定如何实例化一个值,而无需实际实例化它直到需要它。调用代码不必跟踪该值是否已实例化。相反,调用代码仅使用 Value 属性。 (可以使用 IsValueCreated 属性来实例化该值。)

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

这篇关于.NET 4中的延迟初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆