说明
- 通过Init真正生成字典,通过Destroy销毁字典。
- 通过TryGetValue获取目标值,通过TryAdd添加数据,通过Remove删除数据。
- 通过ShowDict打印字典内容。
代码
FanDict.cs
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class FanDict<K, T>
{
[SerializeField]
private FanKeyValue<K, T>[] _keyValueElements;
private Dictionary<K, T> _dict;
public void Init()
{
_dict = new Dictionary<K, T>();
foreach (var e in _keyValueElements)
{
TryAdd(e.Key, e.value);
}
}
public void Destroy()
{
_dict.Clear();
_dict = null;
}
public bool TryGetValue(K key, out T value)
{
return _dict.TryGetValue(key, out value);
}
public bool TryAdd(K key, T value)
{
return _dict.TryAdd(key, value);
}
public bool Remove(K key)
{
return _dict.Remove(key);
}
public void ShowDict()
{
Debug.Log("字典中的元素总数:" + _dict.Keys.Count);
foreach (var key in _dict.Keys)
{
Debug.Log(key + ":" + _dict[key]);
}
Debug.Log("_____________________________________");
}
[System.Serializable]
private class FanKeyValue<M, N>
{
[SerializeField]
private M _key;
public M Key => _key;
[SerializeField]
private N _value;
public N value => _value;
}
}
测试代码
FanTest.cs
using UnityEngine;
public class FanTest : MonoBehaviour
{
[SerializeField]
private int _key;
[SerializeField]
private string _value;
[SerializeField]
private FanDict<int, string> _testDict;
private void Start()
{
_testDict.Init();
}
private void OnDestroy()
{
_testDict.Destroy();
}
private void Update()
{
// 显示字典信息
if (Input.GetKeyDown(KeyCode.A))
{
_testDict.ShowDict();
}
// 获取指定Key对应的值
else if (Input.GetKeyDown(KeyCode.B))
{
if (_testDict.TryGetValue(_key, out string value))
{
Debug.Log("获得指定key对应的value:" + _key + " : " + value);
}
else
{
Debug.Log("字典中不存在key:" + _key);
}
}
// 向字典中新增数据
else if (Input.GetKeyDown(KeyCode.C))
{
if (_testDict.TryAdd(_key, _value))
{
Debug.Log("向字典中新增了数据:" + _key + " : " + _value);
}
else
{
Debug.Log("向字典中添加数据失败:" + _key);
}
}
// 移除数据
else if (Input.GetKeyDown(KeyCode.D))
{
if (_testDict.Remove(_key))
{
Debug.Log("从字典中移除数据:" + _key);
}
else
{
Debug.Log("从字典中移除数据失败:" + _key);
}
}
}
}
网友评论