C#的循环队列

// 
/// 循环缓存区 范型 工具类
/// 
/// 
public class RingBuffer {
	public readonly int Size;
	/// 
    /// 逻辑环填满的响应事件
    /// 
	public Action OnOverflow;
	/// 
    /// 获取计数
    /// 
	public int Count {
		get;
		private set;
	}

	/// 
	/// 
	public int TotalCount {
		get;
		private set;
	}

	private T[] buffer;
	private int position;
	/// 
    /// 构造函数 
    /// 
    /// 大小
	public RingBuffer(int size) {
		this.Size = size;
		this.buffer = new T[size];
		this.Count = 0;
		this.position = 0;
	}
	/// 
    /// 加入
    /// 
    /// 
	public void Push(T item) {
		this.position = (this.position + 1) % this.Size;
		if (this.buffer[this.position] != null && this.OnOverflow != null) {
			this.OnOverflow(this.buffer[this.position]);
		}
		this.buffer[this.position] = item;
		this.Count++;
		if (this.Count > this.Size) {
			this.Count = this.Size;
		}
		this.TotalCount++;
	}
	/// 
    /// 返回
    /// 
    /// 
	public T Peek() {
		if (this.Count == 0) {
			throw new System.InvalidOperationException();
		}
		return this.buffer[this.position];
	}
	/// 
    /// 弹出
    /// 
    /// 
	public T Pop() {
		if (this.Count == 0) {
			throw new System.InvalidOperationException();
		}
		T result = this.buffer[this.position];
		this.buffer[this.position] = default(T);

		this.position = (this.position + this.Size - 1) % this.Size;
		this.Count--;
		this.TotalCount--;

		return result;
	}
	/// 
    /// 是否 存在值
    /// 
    /// 
	public bool Any() {
		return this.Count != 0;
	}
}

你可能感兴趣的:(数据结构,c#)