简体   繁体   English

这个属性初始化的C#模式是什么?

[英]What is this C# pattern for property initialization?

I'll often have objects with properties that use the following pattern: 我经常会有具有使用以下模式的属性的对象:

private decimal? _blah;
private decimal Blah
{
    get
    {
        if (_blah == null)
            _blah = InitBlah();
        return _blah.Value;
    }
}

Is there a name for this method? 这个方法有名字吗?

Lazy initialisation. 懒惰的初始化。

.NET 4, when it arrives, will have a Lazy<T> class built-in. .NET 4,当它到达时,将内置一个Lazy<T>类。

private readonly Lazy<decimal> _blah = new Lazy<decimal>(() => InitBlah());
public decimal Blah
{
    get { return _blah.Value; }
}

Lazy loading, deferred initialization, etc. 延迟加载,延迟初始化等

Noet that InitBlah should (in this case) ideally return decimal , not decimal? Noet, InitBlah应该(在这种情况下)理想地返回decimal ,而不是decimal? to avoid the chance that it gets called lots of times because it is legitimately null. 避免它被多次调用的机会,因为它是合法的null。

这称为延迟初始化

懒惰的初始化程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM