【问题标题】:How to use int array as dictionary key C# [duplicate]如何使用int数组作为字典键C# [重复]
【发布时间】:2021-05-29 11:34:53
【问题描述】:

我试图制作一本字典,但它会使用一对整数作为键。

public Dictionary<int[], car> listOfCells = new Dictionary<int[], car>();

但是当我检查是否有一个值时,它总是返回 false

return listOfCells.ContainsKey(new int[] { x, y })

【问题讨论】:

  • 您应该以 public Dictionary&lt;int, int[]&gt; listOfCells = new Dictionary&lt;int, int[]&gt;(); 的方式创建字典,其中键将是汽车的一些唯一标识符

标签: c# dictionary


【解决方案1】:

数组是引用类型。因此,具有相同内容的两个数组具有两个不同的对象标识并且不“相等”。

如果您的所有数组都有固定数量的元素(例如,如果您使用数组来存储 2D 坐标),请考虑使用using a value tuple

public Dictionary<(int, int), car> listOfCells = new Dictionary<(int, int), car>();

【讨论】:

    猜你喜欢
    • 2016-01-07
    • 2012-02-20
    • 2019-02-12
    • 2017-07-19
    • 2015-06-12
    • 2019-10-25
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    相关资源
    最近更新 更多