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

本文翻譯自:Proper way to initialize a C# dictionary with values?

I am creating a dictionary in a C# file with the following code: 我正在使用以下代碼在C#文件中創建字典:

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: new錯誤下面有一條紅線:

Feature 'collection initilializer' cannot be used because it is not part of the ISO-2 C# language specification 無法使用功能'集合initilializer',因爲它不是ISO-2 C#語言規範的一部分

Can anyone explain what is going on here? 誰能解釋一下這裏發生了什麼?

EDIT: okay, so it turns out I was using .NET version 2. 編輯:好的,所以事實證明我使用的是.NET版本2。


#1樓

參考:https://stackoom.com/question/19WrK/使用值初始化C-字典的正確方法


#2樓

I can't reproduce this issue in a simple .NET 4.0 console application: 我無法在簡單的.NET 4.0控制檯應用程序中重現此問題:

static class Program
{
    static void Main(string[] args)
    {
        var 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. 您似乎可能是針對.NET 2.0(不支持它)或客戶端配置文件框架,而不是支持初始化語法的.NET版本。


#3樓

Object initializers were introduced in C# 3.0, check which framework version you are targeting. 在C#3.0中引入了對象初始化程序,檢查您要定位的框架版本。

Overview of C# 3.0 C#3.0概述


#4樓

With C# 6.0, you can create a dictionary in following way: 使用C#6.0,您可以通過以下方式創建字典:

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

It even works with custom types. 它甚至適用於自定義類型。


#5樓

You can initialize a Dictionary (and other collections) inline. 您可以內聯初始化Dictionary (和其他集合)。 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. 有關詳細信息,請參閱MSDN


#6樓

Suppose we have a dictionary like this 假設我們有這樣的字典

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

We can initialize it as follow. 我們可以按如下方式初始化它。

Dictionary<int, string> dict = new Dictionary<int, string>  
{
    { 1, "Mohan" },
    { 2, "Kishor" },
    { 3, "Pankaj" },
    { 4, "Jeetu" }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章