初始化 C# 哈希表的最简洁方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/841128/
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-05 03:44:12  来源:igfitidea点击:

Most concise way to initialize a C# hashtable

c#hashtable

提问by RexE

Does C# allow hashtables to be populated in one-line expressions? I am thinking of something equivalent to the below Python:

C# 是否允许在单行表达式中填充哈希表?我正在考虑与以下 Python 等效的内容:

mydict = {"a": 23, "b": 45, "c": 67, "d": 89}

In other words, is there an alternative to setting each key-value pair in a separate expression?

换句话说,是否有另一种方法可以在单独的表达式中设置每个键值对?

采纳答案by Andrew Hare

C# 3 has a language extension called collection initializerswhich allow you to initialize the values of a collection in one statement.

C# 3 有一个称为集合初始化器的语言扩展,它允许您在一个语句中初始化集合的值。

Here is an example using a Dictionary<,>:

这是一个使用 a 的示例Dictionary<,>

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var dict = new Dictionary<string, int>
        {
            {"a", 23}, {"b", 45}, {"c", 67}, {"d", 89}
        };
    }
}

This language extension is supported by the C# 3 compiler and any type that implements IEnumerableand has a public Addmethod.

C# 3 编译器和任何实现IEnumerable并具有公共Add方法的类型都支持此语言扩展。

If you are interested I would suggest you read this question I asked here on StackOverflowas to whythe C# team implemented this language extension in such a curious manner (once you read the excellent answers to the question you will see that it makes a lot of sense).

如果您有兴趣,我建议您阅读我在 StackOverflow 上问的这个问题,以了解为什么C# 团队以如此奇怪的方式实现了这种语言扩展(一旦您阅读了该问题的出色答案,您就会发现它使很多感觉)。