2013-03-28 45 views
1

有沒有辦法做到這一點: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。

回答

0

如何計算當你需要它而不是存儲它時,它可以在飛行中完成?

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

你不需要顯式檢查一個空序列; ['Sum'在這種情況下將返回0](http://msdn.microsoft.com/en-gb/library/bb535184.aspx)。 – shambulator

+0

@shambulator這是正確的,但我是絕對無法執行代碼的強大粉絲,不管 – Alex

+0

我會澄清:它被記錄在案*中返回0。我不知道你的支票在保證什麼失敗:) – shambulator

6

如果你想保留類派生的,而不是組成,你應該使用成分,而不是衍生

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

此外,您可以實現IEnumerable的''或IList的''如果您想使用類其中的任意一種方式,而不必繼承'名單'。 –

+0

你的意思是「可選」?我給你upvote,但是,:) – David

+3

那麼,「或者」將意味着,而不是你的答案。我的意思是「另外」,因爲它與你的答案相容。 –

0

,試試這個:

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

然後有人將'BetList'傳遞給'List '的方法,哦,看看我們該死在手裏了!有(幾乎)_ **從來沒有這樣做的一個很好的理由,這不是其中的原因。 –

+0

@BinaryWorrier公平,這是直接回答實際問題的唯一答案,(雖然我不確定當有人問怎樣做某些他們可能不應該做的事情時,該做什麼政策是關於怎麼做的)。 –

+0

@BinaryWorrier你能解釋一下這個解決方案的問題嗎?由於我的主要職位,我注意到List <>有一個Sum方法,但除了我仍然不明白爲什麼這個解決方案有問題。 – labuwx

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 
+0

+1:我不相信我不知道這個!感謝菲爾:) –