有没有办法做到这一点:C#扩展基类的方法
class BetList : List<Bet>
{
public uint Sum { get; private set; }
void Add(Bet bet) : base.Add(bet) // <-- I mean this
{
Sum += bet.Amount;
}
}
我想使用的基地列表类做列表操作。我只想实施Summming。
有没有办法做到这一点:C#扩展基类的方法
class BetList : List<Bet>
{
public uint Sum { get; private set; }
void Add(Bet bet) : base.Add(bet) // <-- I mean this
{
Sum += bet.Amount;
}
}
我想使用的基地列表类做列表操作。我只想实施Summming。
如何计算当你需要它而不是存储它时,它可以在飞行中完成?
class BetList : List<Bet>
{
public uint Sum
{
get { return this.Count > 0 ? this.Sum(bet => bet.Amount) : 0; }
}
}
如果你想保留类派生的,而不是组成,你应该使用成分,而不是衍生
class BetList
{
List<Bet> _internalList=new List<Bet>();
//forward all your related operations to _internalList;
}
此外,您可以实现IEnumerable的''
你的意思是“可选”?我给你upvote,但是,:) – David
那么,“或者”将意味着,而不是你的答案。我的意思是“另外”,因为它与你的答案相容。 –
,试试这个:
class BetList : List<Bet>
{
public uint Sum { get; private set; }
new void Add(Bet bet)
{
base.Add(bet);
Sum += bet.Amount;
}
}
然后有人将'BetList'传递给'List
@BinaryWorrier公平,这是直接回答实际问题的唯一答案,(虽然我不确定当有人问怎样做某些他们可能不应该做的事情时,该做什么政策是关于怎么做的)。 –
@BinaryWorrier你能解释一下这个解决方案的问题吗?由于我的主要职位,我注意到List <>有一个Sum方法,但除了我仍然不明白为什么这个解决方案有问题。 – labuwx
如果您需要扩展现有的集合型你应该使用专门为此设计的Collection<T>
。例如:
public class BetList : Collection<Bet>
{
public uint Sum { get; private set; }
protected override void ClearItems()
{
Sum = 0;
base.ClearItems();
}
protected override void InsertItem(int index, Bet item)
{
Sum += item.Amount;
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
Sum -= item.Amount;
base.RemoveItem(index);
}
protected override void SetItem(int index, Bet item)
{
Sum -= this[i].Amount;
Sum += item.Amount;
base.SetItem(index, item);
}
}
的List<T>
和Collection<T>
之间的差异一个很好的解释可以在这里找到:What is the difference between List (of T) and Collection(of T)?
上面的类将用于这样的:
var list = new BetList();
list.Add(bet); // this will cause InsertItem to be called
+1:我不相信我不知道这个!感谢菲尔:) –
你不需要显式检查一个空序列; ['Sum'在这种情况下将返回0](http://msdn.microsoft.com/en-gb/library/bb535184.aspx)。 – shambulator
@shambulator这是正确的,但我是绝对无法执行代码的强大粉丝,不管 – Alex
我会澄清:它被记录在案*中返回0。我不知道你的支票在保证什么失败:) – shambulator