在 C# 中,
有没有办法将自动属性变成具有指定默认值的延迟加载自动属性?
本质上,我是想把这个...
private string _SomeVariable
public string SomeVariable
{
get
{
if(_SomeVariable == null)
{
_SomeVariable = SomeClass.IOnlyWantToCallYouOnce();
}
return _SomeVariable;
}
}
变成不同的东西,我可以在其中指定默认值,它会自动处理其余部分...
[SetUsing(SomeClass.IOnlyWantToCallYouOnce())]
public string SomeVariable {get; private set;}
最佳答案
不,没有。自动实现的属性仅用于实现最基本的属性:带有 getter 和 setter 的支持字段。它不支持这种类型的自定义。
但是您可以使用 4.0 Lazy<T>
键入以创建此模式
private Lazy<string> _someVariable =new Lazy<string>(SomeClass.IOnlyWantToCallYouOnce);
public string SomeVariable => _someVariable.Value;
此代码将延迟计算 _someVariable
的值第一次Value
表达式被调用。它只会计算一次,并将缓存值以供将来使用 Value
属性
关于C# 延迟加载自动属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4036812/