How do I override List's Add method in C#?

后端 未结 10 1260
名媛妹妹
名媛妹妹 2020-11-27 18:59

I am currently looking to make my own collection, which would be just like a regular list, except that it would only hold 10 items. If an item was added when there were alre

相关标签:
10条回答
  • 2020-11-27 19:17

    Your description of your requirement sounds like a Circular Buffer.

    I implemented my own - similar to this implementation on CodePlex except that mine implements IList<T>.

    Some of the other answers suggest using a Queue<T> - but this isn't quite the same thing, as it only allows FIFO access.

    As a general point, it's not recommended to derive from List<T> - instead derive from Collection<T>, and implement any additional stuff you need. But for a circular buffer it's probably more appropriate to use a private array rather than deriving from Collection<T> like the CodePlex implementation.

    0 讨论(0)
  • 2020-11-27 19:21

    You could extend System.Collections.ObjectModel.Collection and override the InsertItem method to get the behaviour you want, and it also implements IList

    0 讨论(0)
  • 2020-11-27 19:21

    It seems like the best I can do is this:

    class MostRecentList<T> : System.Collections.Generic.List<T> {
            private int capacity;
    
            public MostRecentList(int capacity) : base() {
                this.capacity = capacity;
            }
    
            public new void Add(T item) {
                if (base.Count == capacity) {
                    base.RemoveAt(0);
                }
                base.Add(item);
            }
    }
    

    Since the add() method is not marked as virtual.

    0 讨论(0)
  • 2020-11-27 19:22

    You can also implement the add method via

    public new void Add(...)
    

    in your derived class to hide the existing add and introduce your functionality.

    Edit: Rough Outline...

    class MyHappyList<T> : List<T>
    {
        public new void Add(T item)
        {
            if (Count > 9)
            {
                Remove(this[0]);
            }
    
            base.Add(item);
        }
    }
    

    Just a note, figured it was implied but you must always reference your custom list by the actual type and never by the base type/interface as the hiding method is only available to your type and further derived types.

    0 讨论(0)
  • 2020-11-27 19:22

    You could take a look at the C5 collection library. They have an ArrayList<T> that implements IList<T> and have a virtual Add method. The C5 collection library is an awesome collection of lists, queues, stacks etc... You can find the C5 library here:

    http://www.itu.dk/research/c5/

    0 讨论(0)
  • 2020-11-27 19:26

    You can't override Add(), it is not a virtual method. Derive from IList instead and use a private Queue member for the implementation.

    0 讨论(0)
提交回复
热议问题