我如何重写名单< T>的在C#中添加的方法? [英] How do I override List<T>'s Add method in C#?

查看:166
本文介绍了我如何重写名单< T>的在C#中添加的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在做我自己的收藏,这将是就像一个普通的列表,但它也只能容纳10个项目。如果当有列表中已有10个项目加入一个项目,然后新的项目被追加之前的第一个项目将被删除。

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 already 10 items in the list, then the first item would be removed before the new item was appended.

我想要做的就是创建一个扩展类 System.Collections.Generic.List< T> ,然后修改添加( ŧ项目)方法,包括在必要时用于删除第一项功能。

What I want to do is create a class that extends System.Collections.Generic.List<T>, and then modifies the Add(T item) method to include the functionality which removes the first item if necessary.

推荐答案

首先,你不能覆盖添加,仍然有反对的List ,这意味着如果你使用new关键字和类被转换为一个列表,您的新Add方法将不会被调用。

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.

如果你真的想要的东西像一个名单,但像队列的最大容量工作​​,我建议你实施的 IList的并保持队列的实例来存储你的元素。

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.

例如:

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
}

这篇关于我如何重写名单&LT; T&GT;的在C#中添加的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆