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

dig*_*rld 10 c# arrays indexing

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

$array = array(
    "foo" => "some foo value",
    "bar" => "some bar value",
);
Run Code Online (Sandbox Code Playgroud)

干杯.

Bol*_*ock 28

PHP将数组的概念和字典(也称为哈希表,哈希映射,关联数组)的概念融合到一个array类型中.

在.NET和大多数其他编程环境中,数组总是以数字方式编制索引.对于命名索引,请改用字典:

var dict = new Dictionary<string, string> {
    { "foo", "some foo value" }, 
    { "bar", "some bar value" }
};
Run Code Online (Sandbox Code Playgroud)

与PHP的关联数组不同,.NET中的字典没有排序.如果您需要一个排序字典(但您可能没有),.NET提供了一个排序字典类型.


yoo*_*er8 5

在数组中,没有。但是,有一个非常有用的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.");
}
Run Code Online (Sandbox Code Playgroud)

MSDN 文档 Dictionary<TKey, TValue>