代码之家  ›  专栏  ›  技术社区  ›  Levon Ravel

需要手动添加到词典的帮助

c#
  •  0
  • Levon Ravel  · 技术社区  · 5 年前

            private Dictionary<string, Dictionary<string, string>> packData =
            new Dictionary<string, Dictionary<string, string>>()
            {
                {
                    "Test", //issue here
                    {
                        "Test" , "Test"
                    }
                };
            };
    

    enter image description here

    1 回复  |  直到 5 年前
        1
  •  2
  •   Eric Lippert    5 年前

    您需要明确说明内部字典:

        new Dictionary<string, Dictionary<string, string>>()
        {
            {
                "Test", 
                new Dictionary<string, string> 
                {
                    "Test" , "Test"
                }
            };
        };
    

    这里要遵循的规则是“假设大括号中的内容被替换为调用 Add ". 在你原来的代码中,我们会把这个降到:

        temp = new Dictionary<string, Dictionary<string, string>>();
        temp.Add("Test", { "Test", "Test" });
    

    这不是法律规定。但是

        temp = new Dictionary<string, Dictionary<string, string>>();
        temp.Add("Test", new Dictionary<string, string>(){ "Test", "Test" });
    

    是合法的,并且相应地

        temp = new Dictionary<string, Dictionary<string, string>>();
        temp2 = new Dictionary<string, string>();
        temp2.Add("Test", "Test");
        temp.Add("Test", temp2);
    

    当我感到困惑的时候,我经常发现把代码“放低”成更基本的形式来理解发生了什么。

    在某些情况下,编译器更聪明地理解嵌套大括号的预期含义,如在原始代码中,但不幸的是,这不是其中之一。有关支持和不支持的内容的详细信息,请参阅规范;您将需要搜索“对象初始值设定项”和“集合初始值设定项”。