Mic*_*ael 47 c# associative-array
我没有很多C#的经验,但我习惯在PHP中使用关联数组.
我在C#中看到List类和数组可用,但我想关联一些字符串键.
处理这个问题最简单的方法是什么?
谢谢!
dcp*_*dcp 82
使用Dictionary类.它应该做你需要的.参考在这里.
所以你可以这样做:
IDictionary<string, int> dict = new Dictionary<string, int>();
dict["red"] = 10;
dict["blue"] = 20;
Run Code Online (Sandbox Code Playgroud)
DAG*_*DAG 22
字典可以工作,但.NET内置了关联数组.一个实例是NameValueCollection类(System.Collections.Specialized.NameValueCollection).
与字典相比,一个小优点是,如果您尝试读取不存在的键,它将返回null而不是抛出异常.以下是两种设置值的方法.
NameValueCollection list = new NameValueCollection();
list["key1"] = "value1";
NameValueCollection list2 = new NameValueCollection()
{
{ "key1", "value1" },
{ "key2", "value2" }
};
Run Code Online (Sandbox Code Playgroud)