在 C# 中处理关联数组的最简单方法是什么?

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

What is the easiest way to handle associative array in c#?

c#associative-array

提问by Michael

I do not have a lot of experience with C#, yet I am used of working with associative arrays in PHP.

我对 C# 没有太多经验,但我习惯于在 PHP 中使用关联数组。

I see that in C# the List class and the Array are available, but I would like to associate some string keys.

我看到在 C# 中 List 类和 Array 可用,但我想关联一些字符串键。

What is the easiest way to handle this?

处理这个问题的最简单方法是什么?

Thx!

谢谢!

采纳答案by dcp

Use the Dictionary class. It should do what you need. Reference is here.

使用字典类。它应该做你需要的。参考在这里

So you can do something like this:

所以你可以做这样的事情:

IDictionary<string, int> dict = new Dictionary<string, int>();
dict["red"] = 10;
dict["blue"] = 20;

回答by DAG

A dictionary will work, but .NET has associative arrays built in. One instance is the NameValueCollectionclass (System.Collections.Specialized.NameValueCollection).

字典可以工作,但 .NET 内置了关联数组。一个实例是NameValueCollection类 (System.Collections.Specialized.NameValueCollection)。

A slight advantage over dictionary is that if you attempt to read a non-existent key, it returns null rather than throw an exception. Below are two ways to set values.

与字典相比的一个小优势是,如果您尝试读取一个不存在的键,它会返回 null 而不是抛出异常。下面是两种设置值的方法。

NameValueCollection list = new NameValueCollection();
list["key1"] = "value1";

NameValueCollection list2 = new NameValueCollection()
{
    { "key1", "value1" },
    { "key2", "value2" }
};