Dictionary <string,string [] =“”>的C#对象初始化器应该是什么样的?</string,>

时间:2015-04-01 15:55:52

标签: c# dictionary object-initializers

我正在尝试声明一个值为字符串数组的字典。我怎么能这样做?

我尝试了以下代码(不起作用):

Dictionary<string, string[]> NewDic = new Dictionary<string,string[]>
{
    {"Key_0", {"Value_0.0", "Value_0.1"}},
    {"Key_1", {"Value_1.0", "Value_1.1", "Value_1.2"}},
}

1 个答案:

答案 0 :(得分:9)

您需要指定您的值是以下数组:

使用implicitly typed array

 {"Key_0", new[] {"Value_0.0", "Value_0.1"}},

或明确指定类型

 {"Key_0", new string[] {"Value_0.0", "Value_0.1"}},

所以你的课程看起来像:

public static class NewClass
{
    private static Dictionary<string, string[]> NewDic = new Dictionary<string, string[]>
    {
        {"Key_0", new[] {"Value_0.0", "Value_0.1"}},
        {"Key_1", new string[] {"Value_1.0", "Value_1.1", "Value_1.2"}},
    };
}