Why not inherit from List?

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

    I think I don't agree with your generalization. A team isn't just a collection of players. A team has so much more information about it - name, emblem, collection of management/admin staff, collection of coaching crew, then collection of players. So properly, your FootballTeam class should have 3 collections and not itself be a collection; if it is to properly model the real world.

    You could consider a PlayerCollection class which like the Specialized StringCollection offers some other facilities - like validation and checks before objects are added to or removed from the internal store.

    Perhaps, the notion of a PlayerCollection betters suits your preferred approach?

    public class PlayerCollection : Collection 
    { 
    }
    

    And then the FootballTeam can look like this:

    public class FootballTeam 
    { 
        public string Name { get; set; }
        public string Location { get; set; }
    
        public ManagementCollection Management { get; protected set; } = new ManagementCollection();
    
        public CoachingCollection CoachingCrew { get; protected set; } = new CoachingCollection();
    
        public PlayerCollection Players { get; protected set; } = new PlayerCollection();
    }
    

提交回复
热议问题