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();
}
}
复合结构 队列字典代码(工具类)
最新推荐文章于 2024-03-29 21:32:29 发布