[英]Accessing instance of generic collection from items in collection
我有一個通用集合,它代表一個訂單,每個訂單項都是一個“Item”類對象。 訂單的總價值基於所有訂單項的組合值。 我目前有一種方法可以在檢索到“TotalValue”屬性時獲取訂單的總價值,但我發現這種方法有點不優雅,因為它感覺像是薛定諤的變量; 它只會在觀察時成為總值。
有沒有什么方法可以讓“Item”成員保持在“Quote”集合中,以便在“Item”對象修改自己的成本值時觸發包含它的Quote類實例的“updateValue”方法? item類會自動修改自己的“TotalCost”,但我希望它能夠啟動鏈並同時修改訂單的總成本/價值。
我試圖將其削減以僅保留相關位。
namespace Arbitrary
{
public class Order<T> : IEnumerable<T> where T : Item
{
private List<T> _lines = new List<T>();
private decimal _totalValue;
public decimal TotalValue
{
get { return updateValue(); }
}
private decimal updateValue()
{
_totalValue = 0;
foreach(T Item in _lines)
{
_totalValue += Item.TotalCost;
}
return _totalValue;
}
}
public class Item
{
private decimal _cost;
private int _quantity;
private decimal _totalCost;
public decimal Cost
{
get { return _cost; }
set
{
_cost = value;
_totalCost = (_cost * _quantity);
}
}
public int Quantity
{
get { return _quantity; }
set
{
_quantity = value;
_totalCost = (_cost * _quantity);
}
}
public decimal TotalCost
{
get { return _totalCost; }
}
}
}
更新:由於Blorgbeard的提示, 想出來了 。 我切換了“Item”的構造函數來獲取Quote集合的對象引用(因為它們在沒有Quote集合的情況下永遠不會存在)。 我將“updateValue”方法更改為internal,以便Item類訪問它,因為它們都在同一個程序集中。 更新后的更改已注釋為“// modified”
namespace Arbitrary
{
public class Order<T> : IEnumerable<T> where T : Item
{
private List<T> _lines = new List<T>();
private decimal _totalValue;
public decimal TotalValue
{
get { return updateValue(); }
}
internal decimal updateValue() // modified
{
_totalValue = 0;
foreach(T Item in _lines)
{
_totalValue += Item.TotalCost;
}
return _totalValue;
}
}
public class Item
{
private decimal _cost;
private int _quantity;
private decimal _totalCost;
private Quote<Item> q; // modified
public Item(Quote<Item> q) // modified
{
this.q = q; // modified
}
public decimal Cost
{
get { return _cost; }
set
{
_cost = value;
_totalCost = (_cost * _quantity);
q.updateValue(); // modified
}
}
public int Quantity
{
get { return _quantity; }
set
{
_quantity = value;
_totalCost = (_cost * _quantity);
q.updateValue(); // modified
}
}
public decimal TotalCost
{
get { return _totalCost; }
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.