Why not inherit from List?

前端 未结 27 1755
悲哀的现实
悲哀的现实 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:13

    class FootballTeam : List 
    { 
        public string TeamName; 
        public int RunningTotal;
    }
    

    Previous code means: a bunch of guys from the street playing football, and they happen to have a name. Something like:

    People playing football

    Anyway, this code (from m-y's answer)

    public class FootballTeam
    {
        // A team's name
        public string TeamName; 
    
        // Football team rosters are generally 53 total players.
        private readonly List _roster = new List(53);
    
        public IList Roster
        {
            get { return _roster; }
        }
    
        public int PlayerCount
        {
            get { return _roster.Count(); }
        }
    
        // Any additional members you want to expose/wrap.
    }
    

    Means: this is a football team which has management, players, admins, etc. Something like:

    Image showing members (and other attributes) of the Manchester United team

    This is how is your logic presented in pictures…

提交回复
热议问题