Why not inherit from List?

前端 未结 27 2160
悲哀的现实
悲哀的现实 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条回答
  •  梦毁少年i
    2020-11-21 06:18

    While I don't have a complex comparison as most of these answers do, I would like to share my method for handling this situation. By extending IEnumerable, you can allow your Team class to support Linq query extensions, without publicly exposing all the methods and properties of List.

    class Team : IEnumerable
    {
        private readonly List playerList;
    
        public Team()
        {
            playerList = new List();
        }
    
        public Enumerator GetEnumerator()
        {
            return playerList.GetEnumerator();
        }
    
        ...
    }
    
    class Player
    {
        ...
    }
    

提交回复
热议问题