【问题标题】:Why is Dictionary.ContainsKey returning False when the key is an int[]? [duplicate]为什么当键是 int[] 时 Dictionary.ContainsKey 返回 False? [复制]
【发布时间】:2021-02-02 03:34:30
【问题描述】:

我正在生成一些地图,但遇到了问题。下面是简化的代码。它返回 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,但都没有成功。

【问题讨论】:

  • 数组是引用对象,这意味着除非它们覆盖Equals,否则将使用默认的Object.Equals,它认为两个对象只有在它们实际上是同一个对象时才相等。包含数字 2 的两个数组不相等

标签: c# dictionary reference-type containskey


【解决方案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>();

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

KeyValuePairs 和 ValueTuples 是 value types。您可以通过通常的方式检查这些是否相等。 ContainsKey 将按预期工作。

array 在 C# 中是 reference type。默认情况下,除非它们是同一个对象,否则不会有 2 个数组彼此相等。

【讨论】:

    猜你喜欢
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 2011-03-02
    相关资源
    最近更新 更多