复合结构 队列字典代码(工具类)

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 队列字典
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
public class QueueDictionary<TKey, TValue> {
	/// <summary>
    /// tkey类型队列
    /// </summary>
	private Queue<TKey> queue;
	/// <summary>
    /// tkey tvalue 类型字典
    /// </summary>
	private Dictionary<TKey, TValue> dict;
	/// <summary>
    /// 值类型 委托函数
    /// </summary>
	private Func<TValue> generator;
	/// <summary>
    /// 构造函数 赋值=值类型 委托函数 初始化 队列和字典
    /// </summary>
    /// <param name="generator"></param>
	public QueueDictionary(Func<TValue> generator) {
		this.generator = generator;
		this.queue = new Queue<TKey>();
		this.dict = new Dictionary<TKey, TValue>();
	}
	/// <summary>
	/// 创建一个的头元素(队列peek不删除)
	/// </summary>
	/// <returns>结构体,定义可设置或检索的键/值对</returns>
	public KeyValuePair<TKey, TValue> Peek() {
		return new KeyValuePair<TKey,TValue>(this.queue.Peek(), this.dict[this.queue.Peek()]);
	}
	/// <summary>
    /// 出队列
    /// </summary>
    /// <returns></returns>
	public KeyValuePair<TKey, TValue> Dequeue() {
		var key = this.queue.Dequeue();
		var result = new KeyValuePair<TKey, TValue>(key, this.dict[key]);
		this.dict.Remove(key);
		return result;
	}
	/// <summary>
    /// 是否存在值
    /// </summary>
    /// <returns></returns>
	public bool Any() {
		return this.queue.Count != 0;
	}
	/// <summary>
    /// 扩展方法 根据tkey返回tvalue
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
	public TValue this[TKey key] {
		get {
			if (!this.dict.ContainsKey(key)) {
				this.dict[key] = this.generator.Invoke();
				this.queue.Enqueue(key);
			}
			return this.dict[key];
		}
		set {
			if (!this.dict.ContainsKey(key)) {
				this.queue.Enqueue(key);
			}
			this.dict[key] = value;
		}
	}
	/// <summary>
    /// 清空
    /// </summary>
	public void Clear() {
		this.dict.Clear();
		this.queue.Clear();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值