在Unity3D中写入嵌套字典

Nic*_*ler 1 c# unity-game-engine

我不能直接在嵌套字典中写入值吗?

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

public Dictionary<string, Dictionary<string, Dictionary<string, int>>> planets = 
   new Dictionary<string, Dictionary<string, Dictionary<string, int>>>();

planets[Planet.CharacterId]["MetalMine"]["Level"] = 0;
Run Code Online (Sandbox Code Playgroud)

但是我得到了:

KeyNotFoundException:给定的键不在字典中.

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

Cod*_*ter 5

这是否意味着我必须互相插入我的钥匙?

是的,您需要按顺序初始化每个:

planets[Planet.CharacterId] = new Dictionary<string, Dictionary<string, int>>();
planets[Planet.CharacterId]["MetalMine"] = new Dictionary<string, int>();
planets[Planet.CharacterId]["MetalMine"]["Level"] = 0;
Run Code Online (Sandbox Code Playgroud)

您可以在此处使用集合初始化程序语法,但这不会使内容更具可读性和可维护性.

而不是字典词典的字典,你似乎更好地使用类:

public class Planet
{
    public List<Mine> Mines { get; set; }
}

public class Mine
{
    public string Type { get; set; }
    public int Level { get; set; }
}

var planets = new Dictionary<string, Planet>();

planets[Planet.CharacterId] = new Planet
{
    Mines = new List<Mine>
    {
        new Mine
        {
            Type = "Metal",
            Level = 0
        }
    };
}
Run Code Online (Sandbox Code Playgroud)