使用值初始化C#字典的正确方法?

时间:2013-06-11 15:11:50

标签: c# dictionary

我正在使用以下代码在C#文件中创建字典:

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

new下有一条红线,错误为:

  

无法使用功能'集合initilializer',因为它不是ISO-2 C#语言规范的一部分

有谁能解释这里发生了什么?

编辑:好的,所以事实证明我使用的是.NET版本2.

7 个答案:

答案 0 :(得分:649)

我无法在简单的.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版本。

答案 1 :(得分:169)

使用C#6.0,您可以按以下方式创建字典:

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

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

答案 2 :(得分:31)

您可以内联初始化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 } }
};

有关详细信息,请参阅MSDN

答案 3 :(得分:13)

假设我们有这样的词典

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

答案 4 :(得分:8)

在C#3.0中引入了对象初始化程序,检查您要定位的框架版本。

Overview of C# 3.0

答案 5 :(得分:0)

使用С#6.0

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

答案 6 :(得分:0)

代码看起来不错。只是尝试改变。 Net 框架到 v2.0+