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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17047602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:27:42  来源:igfitidea点击:

Proper way to initialize a C# dictionary with values?

c#dictionary

提问by azrosen92

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 newwith the error:

new错误下方有一条红线:

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

无法使用功能“集合初始化程序”,因为它不是 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。

采纳答案by Haney

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 版本。

回答by Zbigniew

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 概述

回答by Vikram Kumar

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.

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

回答by Brendan

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

您可以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 } }
};

See MSDNfor details.

有关详细信息,请参阅MSDN

回答by Debendra Dash

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

回答by amesh

with c# 6.0

使用 C# 6.0

static class Program
{
    static void Main(string[] args)
    {
        var myDict = new Dictionary<string, string>
        {
           ["Key1"]="Value1",
           ["Key2"]="Value2"
        };

        Console.ReadKey();
    }
}