Why not inherit from List?

前端 未结 27 1713
悲哀的现实
悲哀的现实 2020-11-21 05:39

When planning out my programs, I often start with a chain of thought like so:

A football team is just a list of football players. Therefore, I should

27条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 06:09

    First of all, it has to do with usability. If you use inheritance, the Team class will expose behavior (methods) that are designed purely for object manipulation. For example, AsReadOnly() or CopyTo(obj) methods make no sense for the team object. Instead of the AddRange(items) method you would probably want a more descriptive AddPlayers(players) method.

    If you want to use LINQ, implementing a generic interface such as ICollection or IEnumerable would make more sense.

    As mentioned, composition is the right way to go about it. Just implement a list of players as a private variable.

提交回复
热议问题