C# net Queue 固定長度 不自動擴展大小 不可變大小
C# net 隊列 固定長度 不自動擴展大小 不可變大小
新建文件 QueueLength.cs
拷貝下面的代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.Collections.Generic
{
/// <summary>
/// 表示對象的先進先出集合並固定長度
/// </summary>
/// <typeparam name="T"></typeparam>
public class QueueLength<T> : Queue<T>
{
int length = 1;
/// <summary>
/// 初始化類的新實例,並指定長度
/// </summary>
/// <param name="length">長度</param>
public QueueLength(int length) : base(length)
{
this.length = length;
}
/// <summary>
/// 將對象添加到結尾處
/// </summary>
/// <param name="item">要添加的對象</param>
public new void Enqueue(T item)
{
if (base.Count == length)
base.Dequeue();
base.Enqueue(item);
}
}
}
新建控制台拷貝如下代碼測試
QueueLength<int> aaaa = new QueueLength<int>(3);
aaaa.Enqueue(1);
aaaa.Enqueue(2);
aaaa.Enqueue(3);
aaaa.Enqueue(4);
aaaa.Enqueue(5);
Console.WriteLine(string.Join(",", aaaa));
輸出結果為:

完成
