これを行う方法はありますか:
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 操作を実行したいと考えています。サミングのみを実装したいと思います。
これを行う方法はありますか:
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 操作を実行したいと考えています。サミングのみを実装したいと思います。
派生ではなく合成を使用する必要があります
class BetList
{
List<Bet> _internalList=new List<Bet>();
//forward all your related operations to _internalList;
}
既存のコレクション型を拡張する必要がある場合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
構成ではなくクラスの派生を維持したい場合は、これを試してください:
class BetList : List<Bet>
{
public uint Sum { get; private set; }
new void Add(Bet bet)
{
base.Add(bet);
Sum += bet.Amount;
}
}
保存するのではなく、必要なときにオンザフライで合計を計算するのはどうですか?
class BetList : List<Bet>
{
public uint Sum
{
get { return this.Count > 0 ? this.Sum(bet => bet.Amount) : 0; }
}
}