Skip to content

Dictionary

csharp-dictionary-deep-dive

Dictionary 是什么

Dictionary<TKey, TValue> 是“用 Key 找 Value 的表”。

c
using System.Collections.Generic;

Dictionary<int, string> itemNames = new();

itemNames.Add(1001, "Sword");
itemNames.Add(1002, "Potion");

Debug.Log(itemNames[1001]); // Sword

你可以这样理解:

c
Key      Value
1001  -> Sword
1002  -> Potion
1003  -> Key

两个类型分别是什么意思

Dictionary<int, string>

int 是 Key 类型。 string 是 Value 类型。

也可以是:

c
Dictionary<int, ItemConfig> itemMap;
Dictionary<string, AudioClip> audioMap;
Dictionary<int, GameObject> playerObjects;

Key 必须唯一

同一个 Key 不能重复 Add

c
itemNames.Add(1001, "Sword");
itemNames.Add(1001, "Axe"); // 报错

如果你想新增或覆盖,可以用索引器:

c
itemNames[1001] = "Axe";

读取推荐 TryGetValue

不要上来就写:

c
string name = itemNames[9999]; // Key 不存在会报错

更推荐:

if (itemNames.TryGetValue(1001, out string name))
{
    Debug.Log(name);
}
else
{
    Debug.Log("没有这个道具");
}

遍历 Dictionary

c
foreach (KeyValuePair<int, string> pair in itemNames)
{
    Debug.Log(pair.Key);
    Debug.Log(pair.Value);
}

也可以简单写:

c
foreach (var pair in itemNames)
{
    Debug.Log($"{pair.Key}: {pair.Value}");
}

Unity 里常见用法

最常见是“查表”和“缓存”:

c
Dictionary<int, ItemConfig> itemConfigMap = new();

ItemConfig GetItemConfig(int id)
{
    if (itemConfigMap.TryGetValue(id, out ItemConfig config))
        return config;

    return null;
}

比如: itemId -> 道具配置monsterId -> 怪物配置playerId -> 玩家对象audioName -> AudioClip

Dictionary vs List

List<T> 适合顺序、遍历、可重复。 Dictionary<TKey, TValue> 适合用唯一 Key 快速查找。

如果你经常写:

c
foreach (var item in items)
{
    if (item.id == targetId)
        return item;
}

那很可能可以改成:

c
Dictionary<int, ItemConfig> itemMap;

Unity Inspector 注意

新 Unity 文档已经有 Dictionary 序列化支持说明,但它需要 opt-in,并且 Key / Value 类型有要求。旧项目或通用做法里,仍常用 List<Entry> 包一层给 Inspector 编辑,再运行时转成 Dictionary

参考链接Microsoft DictionaryMicrosoft CollectionsMicrosoft KeyNotFoundExceptionMicrosoft Dictionary.TryGetValueUnity Script Serialization Rules

文章评价

读完这篇,留下你的看法

暂无审核通过的评价。

登录账号后才能评价。

本站访客数0总站访问量0本页访问量0