C#延迟加载的自动属性 [英] C# Lazy Loaded Automatic Properties
问题描述
在C#中,
是否可以将自动属性转换为具有指定默认值的延迟加载的自动属性?
Is there a way to turn an automatic property into a lazy loaded automatic property with a specified default value?
从本质上讲,我正在尝试将此...
Essentially, I am trying to turn this...
private string _SomeVariable
public string SomeVariable
{
get
{
if(_SomeVariable == null)
{
_SomeVariable = SomeClass.IOnlyWantToCallYouOnce();
}
return _SomeVariable;
}
}
更改为其他内容,我可以在其中指定默认值,它会自动处理其余内容...
into something different, where I can specify the default and it handles the rest automatically...
[SetUsing(SomeClass.IOnlyWantToCallYouOnce())]
public string SomeVariable {get; private set;}
推荐答案
没有.自动实现的属性仅用于实现最基本的属性:具有getter和setter的后备字段.它不支持这种类型的自定义.
No there is not. Auto-implemented properties only function to implement the most basic of properties: backing field with getter and setter. It doesn't support this type of customization.
但是,您可以使用4.0 Lazy<T>
类型来创建这种模式
However you can use the 4.0 Lazy<T>
type to create this pattern
private Lazy<string> _someVariable =new Lazy<string>(SomeClass.IOnlyWantToCallYouOnce);
public string SomeVariable => _someVariable.Value;
此代码将在第一次调用Value
表达式时延迟计算_someVariable
的值.它只会被计算一次,并将缓存该值以供将来使用Value
属性
This code will lazily calculate the value of _someVariable
the first time the Value
expression is called. It will only be calculated once and will cache the value for future uses of the Value
property
这篇关于C#延迟加载的自动属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!