문제

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

UPDATE:

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

도움이 되었습니까?

해결책

It is semantically more correct.

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.

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top