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

查看:91
本文介绍了用值初始化 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下有一条红线,报错:

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

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

这里发生了什么?

我使用的是 .NET 版本 2.

I am 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天全站免登陆