我目前正在使用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); –