Proper way to initialize a C# dictionary with values already in it?

I am creating a dictionary in a C# file with the following code:

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

There is a red line under new with the error:

Feature 'collection initilializer' cannot be used because it is not part of the ISO-2 C# language specification

Can anyone explain what is going on here?

EDIT: okay, so it turns out I was using .NET version 2.


I can't reproduce this issue in a simple .NET 4.0 console application:

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

        Console.ReadKey();
    }
}

Can you try to reproduce it in a simple Console application and go from there? It seems likely that you're targeting .NET 2.0 (which doesn't support it) or client profile framework, rather than a version of .NET that supports initialization syntax.


With C# 6.0, you can create a dictionary in following way:

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

It even works with custom types.


You can initialize a Dictionary (and other collections) inline. Each member is contained with braces:

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

See MSDN for details.

链接地址: http://www.djcxy.com/p/21312.html

上一篇: 我正在使用哪个版本的C#

下一篇: 正确的方式来初始化一个C#字典的值已经在它?