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

后端 未结 10 1261
名媛妹妹
名媛妹妹 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:26

    You can just write a class that implements IList<T> that holds an internal List<T> and write your own methods.

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

    First, you can't override Add and still have polymorphism against List, meaning that if you use the new keyword and your class is cast as a List, your new Add method won't be called.

    Second, I suggest you look into the Queue class, as what you are trying to do is more of a queue than it is a list. The class is optimized for exactly what you want to do, but does not have any sort of a size limiter.

    If you really want something to act like a List but work like a Queue with a maximum size, I suggest you implement IList and keep an instance of a Queue to store your elements.

    For example:

    public class LimitedQueue<T> : IList<T>
    {
      public int MaxSize {get; set;}
      private Queue<T> Items = new Queue<T>();
      public void Add(T item)
      {
        Items.Enqueue(item);
        if(Items.Count == MaxSize)
        {
           Items.Dequeue();
        }
      }
      // I'll let you do the rest
    }
    
    0 讨论(0)
  • 2020-11-27 19:31

    Have a read of the Liskov Substitution Principle, your collection is a very poor candidate to extend List<T>, it is not even a great candidate to implement IList<T>.

    What read patterns are required on this data? If you only need to look at all the current entries then implementing IEnumerable<T> and the Add(T) method should be sufficient to start with.

    This can then be implemented by a private Queue (or Deque would be better but such a collection would require some other collections API and I do not suggest you try to implement one yourself) to which you Enqueue() during an Add (with Dequeue's if needed to maintain the size).

    Note that implementing IEnumerable and providing the Add method means you can still use the Collection initialiser syntax if required.

    If you need random access to the values then implementing an indexer may be a good idea but I don't see what benefit this would give you without more context on the question.

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

    You can try to extend System.Collections.ObjectModel.Collection<T>, which is much more flexible. You can then override the protected members InsertItem and SetItem, to customize the behaviour of your collection.

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