針對特殊需要時修改比較方便。
using System;
public class FIFO
...{
private object[] _Buffer;
private float _Grow;
private int _Head;
private int _Tail;
private int _ItemCount;
public int Count ...{ get ...{ return this._ItemCount; } }
public FIFO(int BufferSize, float Grow)
...{
if (BufferSize < 0) ...{ throw new ArgumentOutOfRangeException(); }
if (Grow < 1 || Grow > 10) ...{ throw new ArgumentOutOfRangeException(); }
this._Buffer = new object[BufferSize];
this._Grow = Grow;
}
public FIFO() : this(32, 2) ...{ }
void ChangeBufferSize(int Size)
...{
object[] newbuf = new object[Size];
if (this._ItemCount > 0)
...{
if (this._Head < this._Tail)
...{
Array.Copy(this._Buffer, this._Head, newbuf, 0, this._ItemCount);
}
else
...{
Array.Copy(this._Buffer, this._Head, newbuf, 0, this._Buffer.Length - this._Head);
Array.Copy(this._Buffer, 0, newbuf, this._Buffer.Length - this._Head, this._Tail);
}
}
this._Buffer = newbuf;
this._Head = 0;
this._Tail = this._ItemCount;
}
public void PUT(object obj)
...{
if (this._ItemCount == this._Buffer.Length) //空間不足
...{
int newSize = (int)(this._Buffer.Length * this._Grow);
if (newSize < (this._Buffer.Length + 4)) newSize = this._Buffer.Length + 4;
this.ChangeBufferSize(newSize);
}
this._Buffer[this._Tail] = obj;
this._Tail = (this._Tail + 1) % this._Buffer.Length;
this._ItemCount++;
}
public object GET()
...{
if (this._ItemCount == 0) ...{ throw new InvalidOperationException(); }
object ret = this._Buffer[this._Head];
this._Buffer[this._Head] = null;
this._Head = (this._Head + 1) % this._Buffer.Length;
this._ItemCount--;
return ret;
}
}