用值初始化C#字典的正确方法? [英] Proper way to initialize a C# dictionary with values?

查看:93
本文介绍了用值初始化C#字典的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

new下有一条红线,显示错误:

There is a red line under new with the error:

功能'集合初始化器'不能使用,因为它不是ISO-2 C#语言规范的一部分

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?

好的,原来我使用的是.NET版本2.

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

推荐答案

我无法在简单的.NET 4.0控制台应用程序中重现此问题:

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

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

        Console.ReadKey();
    }
}

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

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.

这篇关于用值初始化C#字典的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆