2016-11-07 118 views
-1

如何在c#中創建多維數組?多維數組與字符串鍵

我想要分配這樣的價值觀:

myArr["level1"]["enemy"][0] = 1; 
myArr["level1"]["enemy"][1] = 4; 

myArr["level1"]["friend"][0] = 2; 
myArr["level1"]["friend"][1] = 3; 

我可以用

public Array level1; 

做正常的陣列和值壓到它。

但我似乎無法做到多維一個

+0

普通數組只用整數索引,所以'myArr [「level1」] [「enemy」] [0] = 1'需要一個自定義索引器。參見例如'詞典<,>'類。 –

+0

1.這不是JavaScript,可能不應該使用這些數據結構。 2.如果你想要的東西接近,請看'Dictionary '。 (https://www.dotnetperls.com/dictionary) –

+1

它可以幫助https://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx https://www.dotnetperls.com/2d –

回答

2

我想你在C#中有最similer事情是一個Dictionary

Dictionary<Person, string> dictionary = new Dictionary<Person, string>(); 
Person myPerson = new Person(); 
dictionary[myPerson] = "Some String"; 
... 
string someString = dictionary[myPerson]; 
Console.WriteLine(someString); // "Some String" 

你可以把字典和builed某種元組結構作爲關鍵字:

public class TwoKeyDictionary<K1,K2,V> 
{ 
    private readonly Dictionary<Pair<K1,K2>, V> _dict; 

    public V this[K1 k1, K2 k2] 
    { 
     get { return _dict[new Pair(k1,k2)]; } 
    } 

    private struct Pair 
    { 
     public K1 First; 
     public K2 Second; 

     public override Int32 GetHashCode() 
     { 
      return First.GetHashCode()^Second.GetHashCode(); 
     } 

     // ... Equals, ctor, etc... 
    } 
} 
+0

謝謝 - 我想我會去字典解決方案。但是,如果我想使用整數來代替關鍵引用,那麼我將如何使用「正常」數組結構來執行此操作:myArr [0] [1] = {0,2,3} - myArr [0] [1] [0] = [1,4,5]?再次感謝你的幫助! –

+0

你做了:)在我的情況下更容易管理xml。我有一個27x15的二維數組,因此使用Dictionary解決方案來記錄所有內容將非常困難。謝謝回答。 –