如何使用int数组作为字典键C# [重复]

Posted

技术标签:

【中文标题】如何使用int数组作为字典键C# [重复]【英文标题】:How to use int array as dictionary key C# [duplicate] 【发布时间】: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;(); 的方式创建字典,其中键将是汽车的一些唯一标识符 【参考方案1】:

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

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

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

【讨论】:

以上是关于如何使用int数组作为字典键C# [重复]的主要内容,如果未能解决你的问题,请参考以下文章