将数组键设置为字符串而不是int?

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

  

你在C#中最接近的是Dictionary

 var dict = new Dictionary(); dict["key_name"] = "value1"; 

请注意, Dictionary与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]; 

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

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

您可以使用Dictionary

 Dictionary dictionary = new Dictionary(); dictionary["key_name"] = "value1"; 

试试字典:

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

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

你的集合inheritance自KeyedCollection,例如……

  public class BlendStates : KeyedCollection { ... 

这要求您重写GetKeyForItem方法。

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

然后,在此示例中,集合由string(BlendState的调试名称)索引:

  OutputMerger.BlendState = BlendStates["Transparent"]; 

由于其他人都说字典,我决定用2个数组回答。 一个数组将是另一个数组的索引。

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

您也没有指定是否希望稍后能够resize。 如果这样做,您将使用List而不是T [] ,其中T是类型,然后根据需要公开一些公共方法以便为每个列表添加。

这是你如何做到的。 这也可以修改为将可能的索引传递给构造函数或者然后执行它。

 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]; } ///  /// Will Throw an IndexOutofRange Exception if you mispell one of the above column titles ///  ///  ///  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"];