unity 字典用法

添加:Dic.Add(key,value);//给字典添加值

删除:Dic.Remove(key);//删除指定值

访问:Dic[key]//表示key所对应的值

判断空:Dic.ContainsKey(key)//判断key是否存在

修改字典的值
   Dictionary<CollectSwitch, bool> collectSwitchValue = new Dictionary<CollectSwitch, bool>();

   
//重置字典所有数值
 public void ResetEvent() 
    {
        List<CollectSwitch> collectSwitches = new List<CollectSwitch>(collectSwitchValue.Keys);
        for (int i = 0; i < collectSwitches.Count; i++)
        {
            collectSwitchValue[collectSwitches[i]] = false;
            Debug.Log($"{collectSwitches[i]}  {collectSwitchValue[collectSwitches[i]]}");
        }
    }

//在不确定key值是否存在的情况下,
//使用字典(Dictionary)的TryGetValue()方法来判断指定键是否存在,如:
    int val;
    if (dic.TryGetValue(key, out val))
    {
        //如果指定的字典的键存在
        dic[key] = newValue;
    }
    else
    {
        //不存在,则添加
        dic.Add(key, newValue);
    }

//还可以使用LINQ来访问字典的键并修改对应的值,如:
Dictionary<string, int> dict = new Dictionary<string, int>();
dict = dict.ToDictionary(x => x.Key, x => x.Value + 1);

猜你喜欢

转载自blog.csdn.net/XYH_78/article/details/132068091