【问题标题】:Inherit from either List or Collection从 List 或 Collection 继承
【发布时间】:2017-01-19 02:32:40
【问题描述】:

谁能解释我为什么不从 IList 继承?我在这里看到很多输入,如果我需要为我的对象而不是从 IList 提供自定义集合类,最好从 Collection 继承。这是为什么?为什么人们说不从 IList 继承?如果可能,请举个例子。

我看到它可能会喜欢这个,所以为什么不使用它作为列表提供更多功能:

class FootballTeam : List<FootballPlayer> 
{ 
}

【问题讨论】:

  • 如果您需要一些自定义功能,则需要从 IList 接口实现,在这种情况下,您必须实现接口的所有方法,但在提供代码 sn-p 中,您只需添加两个属性List 因此两种实现都根据要求而有所不同。从 IList 继承以向集合添加两个属性不值得实现。

标签: c# vb.net


【解决方案1】:

这不提供直接答案,可能有概述

IList 为您提供了实现此功能的灵活性。

public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
{
    T this[int index] { get; set; }

    int IndexOf(T item);
    void Insert(int index, T item);
    void RemoveAt(int index);
}

如果你使用class FootballTeam : List&lt;FootballPlayer&gt; 你可以扩展 FootballTeam 类中的属性。

理想情况下,当您想要扩展您的收藏时,它是必要的。假设你必须实现 AddSort(T item) 然后class FootballTeam : List&lt;FootballPlayer&gt;

如果您使用class FootballTeam : ILIst&lt;FootballPlayer&gt;,您可能会 重新发明 Add()Contains() 应该是的轮子 自己实现

我建议使用Composition over inheritance

class FootballTeam : //So here can use any team base class or anything necessary
{ 
  public string TeamName; 
  public int RunningTotal 

  private List<FootballPlayer> _players
  public IEnumerable<FootballPlayer> Players {get;set;}
}

更新 我已将Players 更新为 IEnumerable,因此会有很大的灵活性。

【讨论】:

  • 还有两个问题: 1) 如果我想使用 Dictionary 怎么办?也可以作为课堂上的财产? 2) 如果您说使用组合更好,但在哪种情况下创建额外的集合类并从 List 或 Collection 继承而不是组合更好?
  • 继承上的组合是基于需求的。想想你想要一个需要特定逻辑的集合的场景,然后你需要在你的类中扩展(实现)List。对于像代表一个类这样的正常情况,最好使用组合
  • @Arie 我已经更新了信息,我想它会解决你关于评论的问题
  • 所以假设我想要特定的逻辑并在 IList 方法的 Add/Remove 中更改某些内容,这样我就可以创建从 List 继承的额外集合类,并在 Add/Remove 方法中添加一些额外的代码,如果我只想按原样使用添加/删除等,然后我可以使用复合材料,我刚才写的对吗?
  • 如果你想覆盖你的派生类,你可以继承 List 并在实现上提供一个新的关键字。有关更多信息,请参阅stackoverflow.com/questions/580202/… method-in-c 和 stackoverflow.com/questions/22165015/…
【解决方案2】:

最好不要全部做,而是像建模一样

class FootballTeam
{ 
    public string TeamName; 
    public int RunningTotal 
    public IList<FootballPlayer> Players
}

如果你想实现一种新的集合,比如 DiskCachedCollection 或其他东西,你通常会继承一个集合

这被称为“组合优于继承”https://en.wikipedia.org/wiki/Composition_over_inheritance

很明显,为什么当一个新的需求出现很长时间时......“我们想要跟踪管理人员与团队的关系”。突然你去嗯嗯,一个团队怎么可能是球员的集合和管理层的集合。哦!不是,一个团队是由球员和管理层组成的

【讨论】:

    【解决方案3】:

    如果您要自定义其具体实现 List 或 Collection 未提供的 List 或 Collection 接口,请实现 IList 或 ICollection 接口,否则使用任何列表或集合“组合优于继承”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 2011-07-09
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      • 2011-02-10
      相关资源
      最近更新 更多