What is this C# pattern for property initialization?
I'll often have objects with properties that use the foll开发者_运维知识库owing 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.
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?
to avoid the chance that it gets called lots of times because it is legitimately null.
Lazy Initialization.
This is called Lazy initialization
lazy initializer
精彩评论