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

后端 未结 10 1324
名媛妹妹
名媛妹妹 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: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 : IList
    {
      public int MaxSize {get; set;}
      private Queue Items = new Queue();
      public void Add(T item)
      {
        Items.Enqueue(item);
        if(Items.Count == MaxSize)
        {
           Items.Dequeue();
        }
      }
      // I'll let you do the rest
    }
    

提交回复
热议问题