如何使用数组值初始化一个字典?

6
我有以下代码:
public static Dictionary<string, string[]> dict = new Dictionary<string, string[]>() {
    "key1", { "value", "another value", "and another" }
};

这是不正确的。错误列表包含以下内容:
没有重载方法'Add'接受3个参数
没有给出与“Dictionary.Add(string,string[])”的必需形式参数'value'相对应的参数
我基本上只想用预设值初始化我的字典。不幸的是,我不能使用代码初始化,因为我正在一个静态类中工作,其中只有变量。
我已经尝试了这些东西:
... {"key1",new string[] {"value","another value","and another"}};
... {"key",(string[]) {"value","another value","and another"}};
但我没有成功。任何帮助都将不胜感激。
PS: 如果我使用两个参数,日志会说无法将字符串转换为字符串[]。
5个回答

13

对我来说这行得通(用另一组{}将你创建的KeyValuePair括起来), 因此它不会找到你试图执行的函数:

Dictionary<string, string[]> dict = new Dictionary<string, string[]>
{
    { "key1", new [] { "value", "another value", "and another" } },
    { "key2", new [] { "value2", "another value", "and another" } }
};

我建议遵循 C# 的 {} 惯例 - 良好的缩进有助于更轻松地发现这些问题 :)


2
不需要使用 string[]。C# 编译器可以从初始化列表中推断出类型。 - Zein Makki

2

您需要用 {} 包围每个键值对,对于 string[] 可以使用 new[]{...}

public static Dictionary<string, string[]> dict = new Dictionary<string, string[]>()
{
    { "key1", new[]{ "value", "another value", "and another" }}
};

1
每个字典条目应该用 {} 括起来,键值对之间应该用 , 分隔。
public static Dictionary<string, string[]> dict = new Dictionary<string, string[]>() 
{
    { "key1", new string[] { "value", "another value", "and another" } },
    { "key2", new string[] { "value", "another value", "and another" } },
};

如果您正在使用C# 6,您可以利用新的语法:
public static Dictionary<string, string[]> dict = new Dictionary<string, string[]>() 
{
    ["key1"] = new string[] { "value", "another value", "and another" },
    ["key2"] = new string[] { "value", "another value", "and another" }
};

0

这种方式不能用于数组初始化。对于匿名类型来说,这是一个失败的尝试:

string[] array = new { "a", "b" }; // doesn't compile

你还缺少一些大括号:

public static Dictionary<string, string[]> dict = new Dictionary<string, string[]>()
{
    { "key1", new []{ "value", "another value", "and another" } }
};

或者:

public static Dictionary<string, string[]> dict = new Dictionary<string, string[]>()
{
    ["key1"] = new []{ "value", "another value", "and another" }
};

0

试一下这个:

Dictionary<string, string[]> dict = new Dictionary<string, string[]>() 
{
    { 
        "key1", new string[] { "value", "another value", "and another" }
    } 
};

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