c#嵌套字典

本文关键字:字典 嵌套 | 更新日期: 2023-09-27 18:04:35

我的语法有什么问题?我希望能够通过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"}
    }}};

c#嵌套字典

不能使用var定义class字段。

Change var to 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关键字及其用法的更多信息,请参阅此处。

在c# 9中,随着目标类型new表达式的引入,可以将字段定义重写为:

public Dictionary<string, Dictionary<string, string>> info = new()
{
    {
        "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"}
        }
    }
};

From MSDN ;

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

  • var不能用于类作用域的字段。

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

只需将var更改为Dictionary<string, Dictionary<string, string>>

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