本文介绍了Lazy T具有什么优点?提供超过标准的懒惰实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此示例,它显示了两种可能的延迟初始化方式.除了线程安全之外,是否有使用Lazy T的任何特定优势.在这里?

Consider this example, it shows two possible ways of lazy initialization. Except for being thread-safe, are there any specific advantates of using Lazy<T> here?

class Customer {
    private decimal? _balance2;
    private static decimal GetBalanceOverNetwork() {
        //lengthy network operations
        Thread.Sleep(2000);
        return 99.9M;
    }

    public decimal? GetBalance2Lazily() {
        return _balance2 ?? (_balance2 = GetBalanceOverNetwork());
    }

    private readonly Lazy<decimal> _balance1 = new Lazy<decimal>(GetBalanceOverNetwork);

    public Lazy<decimal> Balance1 {
        get { return _balance1; }
    }
}

更新:

请以上述代码为简单示例,数据类型无关紧要,这里的重点是比较Lazy< T>.超过标准的延迟初始化.

Please consider above code as a simple example, data types are irrelevant, the point here is to compare Lazy <T> over standard lazy initialization.

推荐答案

从语义上讲更正确.

使用 Nullable< decimal> 时,您说的是 null 的值表示未评估"状态.尽管这是常见的转换,但仍然是任意的.还有数百万种解释 null 的方法,因此您可能应该在某处(在文档中或至少作为注释)解释null在这种情况下的含义.

When you use the Nullable<decimal>, what you say is that the value of null will stand for the "unevaluated" state. Although this is a common conversion, it is still arbitrary. There are million other ways to interpret null, so you should probably explain somewhere (in the documentation or at least as a comment) what null means in this case.

相反,当您使用 Lazy< decimal> 时,您的意图很清楚.

On the contrary, when you use Lazy<decimal>, your intentions are clear.

这篇关于Lazy T具有什么优点?提供超过标准的懒惰实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 15:25