【问题标题】:Can array indexes be named in C#?数组索引可以在 C# 中命名吗?
【发布时间】:2012-04-09 11:39:53
【问题描述】:

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

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

干杯。

【问题讨论】:

  • 你真的想要一个哈希。

标签: c# arrays indexing


【解决方案1】:

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

【讨论】:

    【解决方案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 HeightInInches)
    {
        Console.WriteLine(person.Key + " is " + person.Value + " inches tall.");
    }
    

    MSDN Documentation for Dictionary&lt;TKey, TValue&gt;

    【讨论】:

      【解决方案3】:

      查看 C# 中的Hashtable。这是在 C# 中做你想做的事情的数据结构。

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-01-13
          • 2011-05-02
          • 2019-05-25
          • 1970-01-01
          • 2012-05-01
          • 2014-11-13
          • 1970-01-01
          相关资源
          最近更新 更多