我用下面的代码在c#文件中创建一个字典:

private readonly Dictionary<string, XlFileFormat> FILE_TYPE_DICT
        = new Dictionary<string, XlFileFormat>
        {
            {"csv", XlFileFormat.xlCSV},
            {"html", XlFileFormat.xlHtml}
        };

new下面有一条红线,错误如下:

特性“集合初始化器”不能被使用,因为它不是ISO-2 c#语言规范的一部分

这是怎么回事?

我使用的是。net版本2。


当前回答

假设我们有一个这样的字典:

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "Mohan");
dict.Add(2, "Kishor");
dict.Add(3, "Pankaj");
dict.Add(4, "Jeetu");

我们可以这样初始化它。

Dictionary<int, string> dict = new Dictionary<int, string>
{
    { 1, "Mohan" },
    { 2, "Kishor" },
    { 3, "Pankaj" },
    { 4, "Jeetu" }
};

其他回答

下面是一个Dictionary值的Dictionary示例

            Dictionary<string, Dictionary<int, string>> result = new() {
                ["success"] = new() {{1, "ok"} ,  { 2, "ok" } },
                ["fail"] = new() {{ 3, "some error" }, { 4, "some error 2" } },
            };

这在JSON中是等价的:

{
  "success": {
    "1": "ok",
    "2": "ok"
  },
  "fail": {
    "3": "some error",
    "4": "some error 4"
  }
}

注意,c# 9允许target类型的new表达式,所以如果你的变量或类成员不是抽象类或接口类型的复制可以避免:

    private readonly Dictionary<string, XlFileFormat> FILE_TYPE_DICT = new ()
    {
        { "csv", XlFileFormat.xlCSV },
        { "html", XlFileFormat.xlHtml }
    };

代码看起来很好。只需尝试将. net框架更改为v2.0或更高版本。

使用 С# 6.0

var myDict = new Dictionary<string, string>
{
    ["Key1"] = "Value1",
    ["Key2"] = "Value2"
};

假设我们有一个这样的字典:

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "Mohan");
dict.Add(2, "Kishor");
dict.Add(3, "Pankaj");
dict.Add(4, "Jeetu");

我们可以这样初始化它。

Dictionary<int, string> dict = new Dictionary<int, string>
{
    { 1, "Mohan" },
    { 2, "Kishor" },
    { 3, "Pankaj" },
    { 4, "Jeetu" }
};