c#扩展基类的方法

时间:2013-03-28 12:30:16

标签: c#

有没有办法做到这一点:

class BetList : List<Bet>
{
    public uint Sum { get; private set; }
    void Add(Bet bet) : base.Add(bet)  // <-- I mean this
    {
        Sum += bet.Amount;
    } 
}

我想使用基类List类来执行List操作。我只想实施Summming。

4 个答案:

答案 0 :(得分:6)

你应该使用构图而不是派生

class BetList
{
     List<Bet> _internalList=new List<Bet>();
     //forward all your related operations to _internalList;
}

答案 1 :(得分:2)

如果您需要扩展现有的集合类型,则应使用专为此目的而设计的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

答案 2 :(得分:0)

如果您想保留类派生而不是合成,请尝试以下方法:

class BetList : List<Bet>
{
    public uint Sum { get; private set; }
    new void Add(Bet bet) 
    {
        base.Add(bet);
        Sum += bet.Amount;
    } 
}

答案 3 :(得分:0)

如何在需要时动态计算总和而不是存储它?

class BetList : List<Bet>
{
    public uint Sum 
    { 
        get { return this.Count > 0 ? this.Sum(bet => bet.Amount) : 0; }
    }
}