C#嵌套字典

17

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

4
你遇到了什么编译器错误? - Jim Mischel
2
你在单词 var 处是否遇到了编译错误..? - MethodMan
3
除了实际错误的原因外,为什么你要使用 Dictionary<string, string> 作为值呢?看起来你真正需要的是一个简单的 Chapter 类。 - Jon Skeet
我认为问题出在“var”上,因为它直接在类中使用而不是在方法中使用。我应该使用什么代替? - user1898657
我同意Jon Skeet的观点,我认为创建一个类会是正确的方法,如果他想要一个集合,那么他可以创建一个该类本身的List<T>。 - MethodMan
显示剩余2条评论
2个回答

39

你不能使用 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关键字及其用法的信息。

在C# 9中,引入了目标类型的新表达式,您可以将字段定义重写为:

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"}
        }
    }
};

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>>{}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接