可以在C#中命名数组索引吗?

时间:2012-03-25 21:16:05

标签: c# arrays indexing

我想知道数组的索引是否可以在C#中使用名称而不是默认索引值。我基本上寻找的是以下PHP代码的C#等价物:

$array = array(
    "foo" => "some foo value",
    "bar" => "some bar value",
);

干杯。

4 个答案:

答案 0 :(得分:26)

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

答案 1 :(得分:2)

在数组中,没有。但是,有一个非常有用的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 HeightInInces)
{
    Console.WriteLine(person.Key + " is " + person.Value + " inches tall.");
}

MSDN Documentation for Dictionary<TKey, TValue>

答案 2 :(得分:1)

在C#中查看Hashtable。这是在C#中执行所需的数据结构。

答案 3 :(得分:0)

您可以使用Dictionary<string, FooValue>或类似类型或集合类型,或者,如果您必须坚持使用数组,请使用您的标签定义Enum