我用下面的代码在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。


当前回答

在c# 6.0中,你可以用下面的方法创建字典:

var dict = new Dictionary<string, int>
{
    ["one"] = 1,
    ["two"] = 2,
    ["three"] = 3
};

它甚至适用于自定义类型。

其他回答

您可以内联初始化Dictionary(和其他集合)。每个成员都包含在大括号中:

Dictionary<int, StudentName> students = new Dictionary<int, StudentName>
{
    { 111, new StudentName { FirstName = "Sachin", LastName = "Karnik", ID = 211 } },
    { 112, new StudentName { FirstName = "Dina", LastName = "Salimzianova", ID = 317 } },
    { 113, new StudentName { FirstName = "Andy", LastName = "Ruth", ID = 198 } }
};

有关详细信息,请参阅如何使用集合初始化器初始化字典(c#编程指南)。

使用 С# 6.0

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

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

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

在c# 6.0中,你可以用下面的方法创建字典:

var dict = new Dictionary<string, int>
{
    ["one"] = 1,
    ["two"] = 2,
    ["three"] = 3
};

它甚至适用于自定义类型。

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

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