如何在 C# 中覆盖 List<T> 的 Add 方法? [英] How do I override List&lt;T&gt;&#39;s Add method in C#?

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

问题描述

我目前正在寻找制作我自己的收藏,这就像一个常规列表,只是它只能容纳 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的类,然后将Add(T item)方法修改为包括必要时删除第一项的功能.

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.

推荐答案

首先,您不能覆盖 Add 并且仍然具有针对 List,这意味着如果您使用 new 关键字并且您的类被强制转换为 List,您的新 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.

其次,我建议您查看 Queue 类,如您要做的更多是一个队列而不是一个列表.该类针对您想要做什么进行了优化,但没有任何大小限制器.

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.

如果你真的想要一些像 List 一样的东西但像一个最大大小的队列一样工作,我建议你实现 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
}

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

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