Why not inherit from List?

前端 未结 27 1813
悲哀的现实
悲哀的现实 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 05:56

    Wow, your post has an entire slew of questions and points. Most of the reasoning you get from Microsoft is exactly on point. Let's start with everything about List

    • List is highly optimized. Its main usage is to be used as a private member of an object.
    • Microsoft did not seal it because sometimes you might want to create a class that has a friendlier name: class MyList : List> { ... }. Now it's as easy as doing var list = new MyList();.
    • CA1002: Do not expose generic lists: Basically, even if you plan to use this app as the sole developer, it's worthwhile to develop with good coding practices, so they become instilled into you and second nature. You are still allowed to expose the list as an IList if you need any consumer to have an indexed list. This lets you change the implementation within a class later on.
    • Microsoft made Collection very generic because it is a generic concept... the name says it all; it is just a collection. There are more precise versions such as SortedCollection, ObservableCollection, ReadOnlyCollection, etc. each of which implement IList but not List.
    • Collection allows for members (i.e. Add, Remove, etc.) to be overridden because they are virtual. List does not.
    • The last part of your question is spot on. A Football team is more than just a list of players, so it should be a class that contains that list of players. Think Composition vs Inheritance. A Football team has a list of players (a roster), it isn't a list of players.

    If I were writing this code, the class would probably look something like so:

    public class FootballTeam
    {
        // Football team rosters are generally 53 total players.
        private readonly List _roster = new List(53);
    
        public IList Roster
        {
            get { return _roster; }
        }
    
        // Yes. I used LINQ here. This is so I don't have to worry about
        // _roster.Length vs _roster.Count vs anything else.
        public int PlayerCount
        {
            get { return _roster.Count(); }
        }
    
        // Any additional members you want to expose/wrap.
    }
    

提交回复
热议问题