2013-03-28 56 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:我不相信我不知道这个!感谢菲尔:) –