繁体   English   中英

需要帮助手动添加到字典

[英]Need help manually adding to a dictionary

我很困惑我试图手动将条目添加到字典中,但它在第一个逗号处抛出错误。 感谢您提供任何帮助。

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

在此处输入图片说明

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

    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);

当我感到困惑时,我经常发现将代码“降低”为更基本的形式有助于理解正在发生的事情。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM