具有字符串键的多维数组

本文关键字:数组 字符串 | 更新日期: 2023-09-27 18:16:34

如何在c#中创建多维数组?

我想这样赋值:

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

我可以使用

进行普通数组
public Array level1;

并向其推送值。

但是我似乎不能做多维的

具有字符串键的多维数组

我认为c#中最相似的东西是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" 

您可以使用Dictionary并构建某种元组结构作为键:

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...
    }
}