如何在C#中覆盖列表< T>的Add方法? [英] How do I override List<T>'s Add method in C#?

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

问题描述

我目前正在寻找自己的收藏,这将像一个常规列表,除了它只能保留10项。如果在列表中已经有10个项目时添加了一个项目,则在添加新项目之前将删除第一个项目。



我想要做的是创建扩展 System.Collections.Generic.List< T> 的类,然后修改 Add(T item)

首先,你不能覆盖添加,并且仍然有一个方法来删除第一个项目。

解决方案

针对列表的多态性,这意味着如果您使用新关键字和类转换为List,你的新Add方法不会被调用。



其次,我建议你看看队列类,因为你想要做的是一个队列而不是一个列表。这个类是针对你想做的,但没有任何类型的大小限制器进行了优化。



如果你真的想要某个东西像一个List,但工作方式像一个队列的最大尺寸,我建议你实现 IList ,并保留一个队列的实例来存储您的元素。



例如:

  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 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.

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.

解决方案

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
}

这篇关于如何在C#中覆盖列表&lt; T&gt;的Add方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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