初始化一个字典,键为字符串类型,值为字符串列表类型。

14
我想知道如何声明/初始化一个字典? 以下方式会报错。
Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>()
{
  {"tab1", MyList }
};

List <string> MyList = new List<string>() { "1" };

错误是:字段初始化程序不能引用非静态字段、方法或属性MyList。它不是在字典前面或后面声明列表。


https://dev59.com/rGYq5IYBdhLWcg3wcwSE#14472283 - Parimal Raj
"出现错误". 很好。能分享一下错误信息吗? :/ - Simon Whitehead
3
如果这些是实例字段,仅使用字段初始化程序无法完成。你必须在构造函数中初始化字典。 - Mike Zboray
谢谢。在构造函数中初始化了字典。 - GManika
如果MyList仅作为字典的一部分使用,且永远不必直接引用它,则可以在字典字段初始化器中初始化一个新列表。 - Matthew
3个回答

17
class MyClass
{
    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" } }
    };
}

8

正如 Scott Chamberlain 在 他的回答 中所说:

If these are non static field definitions you can not use the field initializers like that, you must put the data in the constructor.

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 }

};

@SimonWhitehead - 已修复,谢谢! - Parimal Raj

5
如果这些不是静态字段定义,你不能像那样使用字段初始化器,你必须将数据放在构造函数中。
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 }
        };
    }
}

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