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

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

    It seems like the best I can do is this:

    class MostRecentList : System.Collections.Generic.List {
            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.

提交回复
热议问题