C#嵌套词典

时间:2013-03-19 13:43:22

标签: c# dictionary nested

我的语法有什么问题?我希望能够使用此info["Gen"]["name"]

获取值“Genesis”
    public var info = new Dictionary<string, Dictionary<string, string>> {
    {"Gen", new Dictionary<string, string> {
    {"name", "Genesis"},
    {"chapters", "50"},
    {"before", ""},
    {"after", "Exod"}
    }},
    {"Exod", new Dictionary<string, string> {
    {"name", "Exodus"},
    {"chapters", "40"},
    {"before", "Gen"},
    {"after", "Lev"}
    }}};

2 个答案:

答案 0 :(得分:30)

您无法使用var定义类字段。

var更改为Dictionary<string, Dictionary<string, string>>

public Dictionary<string, Dictionary<string, string>> info =
    new Dictionary<string, Dictionary<string, string>>
    {
        {
            "Gen",
            new Dictionary<string, string>
            {
                {"name", "Genesis"},
                {"chapters", "50"},
                {"before", ""},
                {"after", "Exod"}
            }
        },
        {
            "Exod",
            new Dictionary<string, string>
            {
                {"name", "Exodus"},
                {"chapters", "40"},
                {"before", "Gen"},
                {"after", "Lev"}
            }
        }
    };

有关var关键字及其用法的详情,请参阅here

答案 1 :(得分:3)

来自 MSDN ;

  
      
  • var只能在声明和初始化局部变量时使用   在同一声明中;变量无法初始化为null,或   方法组或匿名函数。

  •   
  • var不能用于类范围的字段。

  •   
  • 使用var声明的变量不能在初始化中使用   表达

  •   

只需将var更改为Dictionary<string, Dictionary<string, string>>即可。等;

public Dictionary<string, Dictionary<string, string>> info =
    new Dictionary<string, Dictionary<string, string>>{}