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

For*_*gic 3 c# arrays dictionary

我有以下代码:

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

这是不正确的。错误列表包含以下内容:

方法“Add”没有重载需要 3 个参数

没有给出对应于 'Dictionary.Add(string, string[])' 的所需形式参数 'value' 的参数

我基本上只想用预设值初始化我的字典。不幸的是,我不能使用代码方式初始化,因为我在一个静态类中工作,其中只有变量。

我已经尝试过这些事情:

  • ... {"key1", new string[] {"value", "another value", "and another"}};
  • ... {"key", (string[]) {"value", "another value", "and another"}};

但我没有运气。任何帮助表示赞赏。

PS:如果我使用两个参数,日志会显示can't convert from string to string[].

Gil*_*een 8

这对我有用(周围有另一组{}- 用于KeyValuePair您创建的),因此它找不到您要执行的函数:

Dictionary<string, string[]> dict = new Dictionary<string, string[]>
{
    { "key1", new [] { "value", "another value", "and another" } },
    { "key2", new [] { "value2", "another value", "and another" } }
};
Run Code Online (Sandbox Code Playgroud)

我建议遵循 C#{}约定 - 良好的缩进有助于轻松找到这些问题:)

  • 不需要字符串[]。C# 编译器从初始化列表推断类型。 (2认同)