我用下面的代码在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# 9允许target类型的new表达式,所以如果你的变量或类成员不是抽象类或接口类型的复制可以避免:

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

其他回答

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

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

我不能在一个简单的。net 4.0控制台应用程序中重现这个问题:

static class Program
{
    static void Main(string[] args)
    {
        var myDict = new Dictionary<string, string>
        {
            { "key1", "value1" },
            { "key2", "value2" }
        };

        Console.ReadKey();
    }
}

您可以尝试在一个简单的控制台应用程序中重现它并从那里开始吗?看起来你的目标是。net 2.0(不支持)或客户端配置文件框架,而不是支持初始化语法的。net版本。

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

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

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<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#编程指南)。