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

本文关键字:初始化 字典 数组 何使用 | 更新日期: 2023-09-27 17:57:37

我有以下代码:

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:如果我使用两个参数,日志显示can't convert from string to string[]

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

这对我有效(周围有另一组{}-用于您创建的KeyValuePair),所以它找不到您试图执行的函数:

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

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

您必须包围{}中的每个键值对,您可以将new[]{...}用于string[]:

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 string[] { "value", "another value", "and another" } },
    { "key2", new string[] { "value", "another value", "and another" } },
};

如果你使用的是C#,你可以利用新的语法:

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" }
};

这对数组初始化无效。对于匿名类型来说,这将是一次失败的尝试

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" }
};

试试这个:

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