我想知道如何声明/初始化字典?下面给出了错误.
Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>()
{
{"tab1", MyList }
};
List <string> MyList = new List<string>() { "1" };
Run Code Online (Sandbox Code Playgroud)
错误是:字段初始值设定项不能引用非静态字段,方法或属性MyList.它不是字典前面或后面的List声明.
Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>()
{
{"tab1", new List<string> { "1" } },
{"tab2", new List<string> { "1","2","3" } },
{"tab3", new List<string> { "one","two" } }
};
Run Code Online (Sandbox Code Playgroud)
正如斯科特张伯伦在答案中所说:
如果这些是非静态字段定义,则不能使用这样的字段初始值设定项,则必须将数据放在构造函数中.
Run Code Online (Sandbox Code Playgroud)class MyClass { Dictionary<string, List<string>> myD; List <string> MyList; public MyClass() { MyList = new List<string>() { "1" }; myD = new Dictionary<string, List<string>>() { {"tab1", MyList } }; } }
另外对于静态场
private static List<string> MyList = new List<string>()
{
"1"
};
private static Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>()
{
{"tab1", MyList }
};
Run Code Online (Sandbox Code Playgroud)
如果这些是非静态字段定义,则不能像这样使用字段初始值设定项,必须将数据放入构造函数中。
class MyClass
{
Dictionary<string, List<string>> myD;
List <string> MyList;
public MyClass()
{
MyList = new List<string>() { "1" };
myD = new Dictionary<string, List<string>>()
{
{"tab1", MyList }
};
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14205 次 |
| 最近记录: |