T>与解答其中的限制大小;在.NET?大小、GT、NET

2023-09-02 21:08:46 作者:闷骚小妮子

我有一个队列< T>我已经初始化为一个容量为2,但显然这只是能力,并不断扩大我添加的项目对象。是否已有一个对象,它会自动离队,当达到限制的项目,或者是最好的解决方案,以创建自己的继承类?

I have a Queue<T> object that I have initialised to a capacity of 2, but obviously that is just the capacity and it keeps expanding as I add items. Is there already an object that automatically dequeues an item when the limit is reached, or is the best solution to create my own inherited class?

推荐答案

我'已经敲了我要找的基本版本,它并不完美,但它会做的工作,直到更好的东西走来。

I've knocked up a basic version of what I'm looking for, it's not perfect but it'll do the job until something better comes along.

public class LimitedQueue<T> : Queue<T>{    private int limit = -1;    public int Limit    {        get { return limit; }        set { limit = value; }    }    public LimitedQueue(int limit)        : base(limit)    {        this.Limit = limit;    }    public new void Enqueue(T item)    {        if (this.Count >= this.Limit)        {            this.Dequeue();        }        base.Enqueue(item);    }}