队列的限制大小<T>在.NET 中? [英] Limit size of Queue<T> in .NET?

查看:24
本文介绍了队列的限制大小<T>在.NET 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个队列<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>
{
    public int Limit { get; set; }

    public LimitedQueue(int limit) : base(limit)
    {
        Limit = limit;
    }

    public new void Enqueue(T item)
    {
        while (Count >= Limit)
        {
            Dequeue();
        }
        base.Enqueue(item);
    }
}

这篇关于队列的限制大小&lt;T&gt;在.NET 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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