我喜欢编写许多小的 getter 属性来准确描述它们的含义。
然而,这可能会导致重复且昂贵的计算。
我所知道的避免这种情况的所有方法都会降低代码的可读性。
伪代码示例:
ctor(decimal grossAmount, taxRateCalculator, itemCategory)
{
// store the ctor args as member variables
}
public decimal GrossAmount { get { return _grossAmount, } }
private decimal TaxRate { get { return _taxRateCalculater.GetTaxRateFor(_itemCategory); } } // expensive calculation
public decimal TaxAmount { get { return GrossAmount * TaxRate; } }
public decimal NetAmount { get { return GrossAmount - TaxAmount; } }
在这个例子中,每个属性的作用非常明显,因为它们是简单的访问器。 TaxRate 已被重构为它自己的属性,因此它的作用也很明显。如果_taxRateCalculator操作非常昂贵,如何避免重复执行而不浪费代码?
在我的真实场景中,我可能有十个字段需要以这种方式处理,因此十组 _backing 或 Lazy 字段会很丑陋。
最佳答案
缓存值
private decimal? _taxRate = null;
...
private decimal TaxRate
{
get
{
if (!this._taxRate.HasValue) {
this._taxRate = _taxRateCalculator.GetTaxRateFor(_itemCategory);
}
return this._taxRate.Value;
}
}
关于c# - 如何设计基于 getter 的小型类而不需要多次执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24820213/