【问题标题】:Set array key as string not int?将数组键设置为字符串而不是int?
【发布时间】:2025-12-19 22:50:11
【问题描述】:

我正在尝试将数组键设置为字符串,如下例所示,但在C#

<?php
$array = array();
$array['key_name'] = "value1";
?>

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    你在 C# 中最接近的是Dictionary&lt;TKey, TValue&gt;

    var dict = new Dictionary<string, string>();
    dict["key_name"] = "value1";
    

    请注意,Dictionary&lt;TKey, TValue&gt; 与 PHP 的关联数组相同,因为它可以通过一种类型的键 (TKey - 这是string 在上面的例子中),而不是字符串/整数键的组合(感谢 Pavel 澄清这一点)。

    也就是说,我从未听过 .NET 开发人员对此抱怨过。


    回应您的评论:

    // The number of elements in headersSplit will be the number of ':' characters
    // in line + 1.
    string[] headersSplit = line.Split(':');
    
    string hname = headersSplit[0];
    
    // If you are getting an IndexOutOfRangeException here, it is because your
    // headersSplit array has only one element. This tells me that line does not
    // contain a ':' character.
    string hvalue = headersSplit[1];
    

    【讨论】:

    • 您确定按索引访问是关联数组定义的一部分吗?见en.wikipedia.org/wiki/Associative_array
    • @Odrade:我根本不是;)这就是为什么我编辑我的答案以专门提到“PHP 的关联数组”(可能就在您发表评论之后)。
    • @Odrade:在 PHP 数组的情况下,它们不能真正“按索引”访问 - 相反,整数可以是字符串旁边的键(并且有一个非常复杂的转换方案,例如8"8" 是同一个键,但 "08" 不是)。它们不是索引,因为它们不能识别数组中元素的位置。
    • 我现在抛出一个错误:“索引超出了数组的范围。”。有任何想法吗?? var headers = new Dictionary<string string>();<br> string[] headersSplit = line.Split(':');<br> string hname = headersSplit[0];<br> string hvalue =标头拆分[1]; headers[hname] = hvalue;<br> Console.WriteLine("Header added: {0} {1}", hname, hvalue);<br></string>
    • @arbme:您要拆分的文本不得包含“:”字符。请参阅我的答案底部的更新。
    【解决方案2】:

    嗯,我猜你想要一本字典:

    using System.Collections.Generic;
    
    // ...
    
    var dict = new Dictionary<string, string>();
    dict["key_name1"] = "value1";
    dict["key_name2"] = "value2";
    string aValue = dict["key_name1"];
    

    【讨论】:

      【解决方案3】:

      你可以使用Dictionary&lt;TKey, TValue&gt;:

      Dictionary<string, string> dictionary = new Dictionary<string, string>();
      dictionary["key_name"] = "value1";
      

      【讨论】:

        【解决方案4】:

        试试字典:

        var dictionary = new Dictionary<string, string>();
        dictionary.Add("key_name", "value1");
        

        【讨论】:

          【解决方案5】:

          您还可以使用 KeyedCollection http://msdn.microsoft.com/en-us/library/ms132438%28v=vs.110%29.aspx,其中您的值是复杂类型并具有唯一属性。

          您的集合继承自 KeyedCollection,例如 ...

              public class BlendStates : KeyedCollection<string, BlendState>
              {
              ...
          

          这需要您覆盖 GetKeyForItem 方法。

              protected override string GetKeyForItem(BlendState item)
              {
                  return item.DebugName;
              }
          

          那么,在这个例子中,集合是通过字符串(BlendState 的调试名称)来索引的:

              OutputMerger.BlendState = BlendStates["Transparent"];
          

          【讨论】:

            【解决方案6】:

            因为其他人都说字典,所以我决定用 2 个数组来回答。 一个数组将是另一个数组的索引。

            您并没有真正指定在特定索引处可以找到的数据类型,因此我继续选择字符串作为示例。

            您也没有指定是否希望以后能够调整它的大小。如果这样做,您将使用 List&lt;T&gt; 而不是 T [] 其中 T 是类型,然后根据需要为每个列表公开一些用于 add 的公共方法。

            您可以这样做。这也可以修改为将可能的索引传递给构造函数,或者按照您的意愿进行设置。

            class StringIndexable
            {
            //you could also have a constructor pass this in if you want.
                   public readonly string[] possibleIndexes = { "index1", "index2","index3" };
                private string[] rowValues;
                public StringIndexable()
                {
                    rowValues = new string[ColumnTitles.Length];
                }
            
                /// <summary>
                /// Will Throw an IndexOutofRange Exception if you mispell one of the above column titles
                /// </summary>
                /// <param name="index"></param>
                /// <returns></returns>
                public string this [string index]
                {
                    get { return getOurItem(index); }
                    set { setOurItem(index, value); }
            
            
                }
            
                private string getOurItem(string index)
                {
                    return rowValues[possibleIndexes.ToList().IndexOf(index.ToLower())];
            
                }
                private void setOurItem(string index, string value)
                {
                    rowValues[possibleIndexes.ToList().IndexOf(index.ToLower())] = value;
                }
            
            }
            

            然后你可以这样称呼它:

              StringIndexable YourVar = new YourVar();
              YourVar["index1"] = "stuff";
              string myvar = YourVar["index1"];
            

            【讨论】: