0

我正在处理一些地图生成,但我遇到了一个问题。下面是简化的代码。它返回 False 而它应该返回 True。

static Dictionary<int[], Tile> map = new Dictionary<int[], Tile>();

static bool GenerateMap()
{
    

    for (int y = 0; y < 3; y++)
    {
        for (int x = 0; x < 3; x++)
        {
            Tile tile;
            int[] i = {x, y};
            if(map.ContainsKey(i))
            {
                
                tile = map[i];
                Console.WriteLine("Contains!");
            
            }
            else
            {   
                tile = new Tile();
                tile.Generate();
                map.Add(i, tile);                
            }
       
        }
    }
    int[] z = {0,0};
    if (map.ContainsKey(z)) return true;

    return false;
}

我尝试过 Dictionary.TryGetValue() 和 Try / Catch,但都没有奏效。

4

1 回答 1

1

更改此行:

static Dictionary<int[], Tile> map = new Dictionary<int[], Tile>();

将字典键设为KeyValuePairValueTuple而不是int[]

static Dictionary<KeyValuePair<int, int>, Tile> map = new Dictionary<KeyValuePair<int, int>, Tile>();

或者

static Dictionary<(int x, int y), Tile> map = new Dictionary<(int x, int y), Tile>();

然后在整个代码中使用它。

KeyValuePairValueTuple值类型。您可以通过通常的方式检查这些是否相等。ContainsKey将按预期工作。

数组是 C# 中的引用类型。默认情况下,没有 2 个数组彼此相等,除非它们是同一个对象。

于 2020-10-21T03:06:28.980 回答