C# 嵌套字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15501202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# nested dictionaries
提问by user1898657
What is wrong with my syntax? I want to be able to get the value "Genesis" with this info["Gen"]["name"]
我的语法有什么问题?我希望能够通过这个获得“Genesis”的价值info["Gen"]["name"]
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"}
}}};
采纳答案by Mohammad Dehghan
You cannot define a class field using var
.
您不能使用 定义类字段var
。
Change var
to Dictionary<string, Dictionary<string, string>>
:
更改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"}
}
}
};
See herefor more information about var
keyword and its usage.
有关关键字及其用法的更多信息,请参见此处var
。
回答by Soner G?nül
From MSDN
;
来自MSDN
;
var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
var cannot be used on fields at class scope.
Variables declared by using var cannot be used in the initialization expression.
var 只能在同一个语句中声明和初始化局部变量时使用;该变量不能初始化为 null,也不能初始化为方法组或匿名函数。
var 不能用于类范围内的字段。
使用 var 声明的变量不能在初始化表达式中使用。
Just change your var
to Dictionary<string, Dictionary<string, string>>
. Like;
只需将您的更改var
为Dictionary<string, Dictionary<string, string>>
. 喜欢;
public Dictionary<string, Dictionary<string, string>> info =
new Dictionary<string, Dictionary<string, string>>{}