1

これを行う方法はありますか:

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 操作を実行したいと考えています。サミングのみを実装したいと思います。

4

4 に答える 4

6

派生ではなく合成を使用する必要があります

class BetList
{
     List<Bet> _internalList=new List<Bet>();
     //forward all your related operations to _internalList;
}
于 2013-03-28T12:31:18.353 に答える
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>との違いのわかりやすい説明は、 List (of T) と Collection(of T) の違いCollection<T>何ですか?

上記のクラスは次のように使用されます。

var list = new BetList();
list.Add( bet );  // this will cause InsertItem to be called
于 2013-03-28T12:43:03.353 に答える
0

構成ではなくクラスの派生を維持したい場合は、これを試してください:

class BetList : List<Bet>
{
    public uint Sum { get; private set; }
    new void Add(Bet bet) 
    {
        base.Add(bet);
        Sum += bet.Amount;
    } 
}
于 2013-03-28T12:36:39.210 に答える
0

保存するのではなく、必要なときにオンザフライで合計を計算するのはどうですか?

class BetList : List<Bet>
{
    public uint Sum 
    { 
        get { return this.Count > 0 ? this.Sum(bet => bet.Amount) : 0; }
    }
}
于 2013-03-28T13:12:21.697 に答える