在 Unity3D 中写入嵌套字典

我不能直接将值写入我的嵌套字典吗?


如果我能像这样访问它会很好:


public Dictionary<string, Dictionary<string, Dictionary<string, int>>> planets = 

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


planets[Planet.CharacterId]["MetalMine"]["Level"] = 0;

但我得到:


KeyNotFoundException: 字典中不存在给定的键。


这是否意味着我必须Keys互相插入?


慕无忌1623718
浏览 321回答 2
2回答

慕桂英4014372

这是否意味着我必须依次插入我的密钥?是的,您需要按顺序初始化每个:planets[Planet.CharacterId] = new Dictionary<string, Dictionary<string, int>>();planets[Planet.CharacterId]["MetalMine"] = new Dictionary<string, int>();planets[Planet.CharacterId]["MetalMine"]["Level"] = 0;您可以在此处使用集合初始值设定项语法,但这不会使内容更具可读性和可维护性。您似乎最好使用一个类,而不是字典的字典:public class Planet{&nbsp; &nbsp; public List<Mine> Mines { get; set; }}public class Mine{&nbsp; &nbsp; public string Type { get; set; }&nbsp; &nbsp; public int Level { get; set; }}var planets = new Dictionary<string, Planet>();planets[Planet.CharacterId] = new Planet{&nbsp; &nbsp; Mines = new List<Mine>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; new Mine&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Type = "Metal",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Level = 0&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };}

撒科打诨

它可能有帮助或嵌套字典替代。创建 Sample.cs 脚本并对其进行测试。&nbsp;public Dictionary<string,Tuple<string,string,string,int>> _planets = new Dictionary<string, Tuple<string,string, string, int>>();void Start()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;string myKey = string.Concat("1","MetalMine","Level");&nbsp; &nbsp; &nbsp; &nbsp;if(!_planets.ContainsKey(myKey))&nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;_planets.Add(myKey,Tuple.Create("1","MetalMine","Level",0));&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;Debug.Log("_planets mykey "+myKey+" ==> "+_planets[myKey].Item4);&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP