列出限量项目

Mr.*_*.Pe 4 c# generics queue list

我需要保持短暂的价值观.所以我需要一个包含最多项目数的列表.我希望它能够接受新的添加,即使它已经满了.在这种情况下,我希望我添加的最旧的项目丢失.我找不到任何适合这个目的的课程然后自己做了.我一定会在以后添加方法,但现在我有我需要的东西.

所以我的第一个问题是:它是一个正确的代码:http://pastebin.com/0BCbyNqJ 这个类看起来足够干净了吗?

我的第二个问题是关于我抛出的这些例外情况.

/// <summary>
/// Oldest item added to the list
/// </summary>
public T First
{
    get
    {
        if (_head < 0)
            throw new IndexOutOfRangeException("The list is empty");

        if (_firstRoundDone)
            return _array[(_head + 1) % _max];
        else
            return _array[0];
    }
}
Run Code Online (Sandbox Code Playgroud)

在将任何内容添加到我的列表之前,我希望调用First,LastCount返回null.我认为这会更有意义.但我不知道怎么做,因为返回类型是int或T,我不想添加像这样的约束where T:Nullable.由于我没有看到任何解决方案,我想知道Exception是不是,毕竟是最优雅的方式.或者我应该实现类似GetFirst(out T first)甚至是TryGetFirst(out T)什么方法?

Ale*_*lex 14

扩展Queue<>会生成一个非常短的代码,如下所示:

public class Buffer<T> : Queue<T>
{
    private int? maxCapacity { get; set; }

    public Buffer() { maxCapacity = null; }
    public Buffer(int capacity) { maxCapacity = capacity; }

    public void Add(T newElement)
    {
        if (this.Count == (maxCapacity ?? -1)) this.Dequeue(); // no limit if maxCapacity = null
        this.Enqueue(newElement);
    }
}
Run Code Online (Sandbox Code Playgroud)

.Clear()并且.ToList()将被继承,不需要实现它们.