【发布时间】:2012-04-09 11:39:53
【问题描述】:
我想知道是否可以在 C# 中为数组的索引指定名称而不是默认索引值。我基本上在寻找的是以下 PHP 代码的 C# 等效项:
$array = array(
"foo" => "some foo value",
"bar" => "some bar value",
);
干杯。
【问题讨论】:
-
你真的想要一个哈希。
我想知道是否可以在 C# 中为数组的索引指定名称而不是默认索引值。我基本上在寻找的是以下 PHP 代码的 C# 等效项:
$array = array(
"foo" => "some foo value",
"bar" => "some bar value",
);
干杯。
【问题讨论】:
PHP 将数组的概念和字典的概念(又名哈希表、哈希映射、关联数组)融合到一个 array type 中。
在 .NET 和大多数其他编程环境中,数组总是按数字索引。对于命名索引,请改用dictionary:
var dict = new Dictionary<string, string> {
{ "foo", "some foo value" },
{ "bar", "some bar value" }
};
与 PHP 的关联数组不同,.NET 中的字典没有排序。如果您需要排序字典(但您可能不需要),.NET 提供了一个sorted dictionary type。
【讨论】:
在数组中,没有。但是,有一个非常有用的Dictionary 类,它是KeyValuePair 对象的集合。它类似于数组,因为它是带有键的对象的可迭代集合,但更通用的是键可以是任何类型。
例子:
Dictionary<string, int> HeightInInches = new Dictionary<string, int>();
HeightInInches.Add("Joe", 72);
HeightInInches.Add("Elaine", 60);
HeightInInches.Add("Michael", 59);
foreach(KeyValuePair<string, int> person in HeightInInches)
{
Console.WriteLine(person.Key + " is " + person.Value + " inches tall.");
}
【讨论】:
查看 C# 中的Hashtable。这是在 C# 中做你想做的事情的数据结构。
【讨论】:
您可以使用 Dictionary<string, FooValue> 或类似类型或集合类型,或者,如果您必须坚持使用数组,请使用您的标签定义 Enum。
【讨论】: