/******************************************************************** 文件: DictionaryEx.cs 作者: 梦语 邮箱: 1982614048@qq.com 创建时间: 2024/03/29 17:28:19 最后修改: 梦语 最后修改时间: 2024/04/03 16:04:19 功能: 自定义顺序字典 *********************************************************************/ using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Ether { [Serializable] public class SerializeKeyValue { public TKey Key; public TValue Value; public SerializeKeyValue(TKey key, TValue value) { this.Key = key; this.Value = value; } } [Serializable] public class DictionaryEx : Dictionary, ISerializationCallbackReceiver where TKey : IComparable { [SerializeField] private List> allData = new List>(); public DictionaryEx() : base() { } public DictionaryEx(DictionaryEx dic) : base(dic) { } public new List Keys { get { List temp = new List(); foreach (var item in allData) { temp.Add(item.Key); } return temp; } } public new List Values { get { List temp = new List(); foreach (var item in allData) { temp.Add(item.Value); } return temp; } } public new void Add(TKey key, TValue value) { Remove(key); base.Add(key, value); allData.Add(new SerializeKeyValue(key, value)); } public new void Remove(TKey key) { if (!base.ContainsKey(key)) return; base.Remove(key); var pair = GetKeyValuePair(key); if (pair != null) { allData.Remove(pair); } } public void SetAsLastSibling(TKey key) { var pair = GetKeyValuePair(key); if (pair == null) return; Remove(key); Add(key, pair.Value); } public void SetAsFirstSibling(TKey key) { var pair = GetKeyValuePair(key); if (pair == null) return; allData.Remove(pair); allData.Insert(0, pair); } public new TValue this[TKey key] { get { if (base.ContainsKey(key)) { return base[key]; } else { Debug.LogError("字典中没有该key值:" + key); } return default; } set => Add(key, value); } public TValue this[int index] { get { if (Keys.Count > index) { return this[Keys[index]]; } else { Debug.LogError("字典中没有该索引值:" + index); } return default; } } public SerializeKeyValue GetKeyValuePair(TKey key) { return allData.FirstOrDefault(s => s.Key.CompareTo(key) == 0); } public new void Clear() { base.Clear(); allData.Clear(); } public IEnumerator GetKeys() { return Keys.GetEnumerator(); } public new IEnumerator> GetEnumerator() { for (int i = 0; i < allData.Count; i++) { yield return allData[i]; } } public void OnBeforeSerialize() { } public void OnAfterDeserialize() { base.Clear(); foreach (var kvp in allData) { if (!base.ContainsKey(kvp.Key)) { base.Add(kvp.Key, kvp.Value); } else { Debug.LogError("key值重复:" + kvp.Key); } } } } }