我目前正在使用C#編寫應用程序。想象一下帶有結帳的店面。我有一個對象作爲鍵和int對象計數器作爲值字典結構。C#字典計算組值的總和
的結構是這樣的:
Dictionary<myObject, int> items.
的基本思路是,通過項目的字典進入的方法。我只向字典中添加獨特的myObjects。 myObject附有一個計數器規則。一旦計數器規則滿了,我想用字典中的所有myObects進行計算。
的myObject的是這樣的:
public class myObject
{
string ItemId { get; set; }
Discount Discount { get; set; }
}
public class Discount
{
public int Count { get; set; }
public decimal Price { get; set; }
public IDiscountHandler DiscountHandler => new DiscountHandler();
}
樣本myObject的看起來是這樣的:
var myObectA = new myObject()
{
ItemId = "A"
};
var discountA = new Discount()
{
Count = 2,
Price = 12 // special price, if 2 myObjects were added to the Dictionary
};
myObjectA.Discount = discountA;
1)我填的項目字典,並把它傳遞給處理方法:
private decimal _totalDiscountedValue { get; set; } = 0;
if (!_items.ContainsKey(myObject))
{
_items.Add(myObject, 1);
}
else
{
_items[myObject]++;
}
_totalDiscountedValue += _discountHandler.CalculateDiscount(_items);
2)在我的處理程序中,我試圖總結所有的折扣值,一旦計數器規則滿了。但在這裏我很苦惱:
public class DiscountHandler : DiscountHandler
{
private decimal _totalDiscount { get; set; } = 0;
public override decimal CalculateDiscount(IDictionary<myObject, int> items)
{
if (items == null) throw new ArgumentNullException(nameof(items));
// I'm struggeling here:
// check if Dictionary[i].Dicount.Count = Dictionary.Value
// then _totalDiscount += Dictionary[i].Discount.Price
return _totalDiscount;
}
}
你知道如何解決這個問題,或者你有如何解決這個問題的想法?
非常感謝!
_totalDiscountedValue = _totalDiscountedValue + _discountHandler.CalculateDiscount(_items); –