哪个更好 ???
public class Order { private double _price; private double _quantity; public double TotalCash { get { return _price * _quantity; } }
要么
public class Order { private double _totalCash; private double _price; private double _quantity; private void CalcCashTotal() { _totalCash = _price * _quantity } public double Price { set { _price = value; CalcCashTotal(); } } public double Quantity { set { _price = value; CalcCashTotal(); } } public double TotalCash { get { return _totalCash; } }
解决方法
有权衡.如果计算简单,不需要很长时间,就把它放在get中.它使您的生活变得更轻松,因为您不用担心总体价格所依赖的每一套物品都会进行检查,这可能会导致错误.
如果计算需要很多时间,那么您也可以采取混合方式.您可以在所有依赖集中设置一个IsDirtyTotalPrice布尔值,然后在get中进行计算并缓存它,以便只需要在需要时计算变量.你不会在集合中进行计算,因为可能会有很多的计算,并且你可以尽可能多地进行计算.
public class Order { private double _totalCash; private double _price; private double _quantity; private _IsDirtyTotalCash = true; private void CalcCashTotal() { _totalCash = _price * _quantity } public double Price { set { _price = value; _IsDirtyTotalCash = true; } } public double Quantity { set { _price = value; _IsDirtyTotalCash = true; } } public double TotalCash { get { if(_IsDirtyTotalCash) { _totalCash = CalcTotalCost(); _isDirtyTotalCash = false; } return _totalCash; } } }