我遇到这样一种情况,我需要一个包含这种类型键的字典,但后来似乎找不到等效的键。
Dictionary<Tuple<int[], int>, object> cache = new Dictionary<Tuple<int[], int>, object>();
cache.Add(Tuple.Create(new int[]{1}, 1), new object());
Assert.That(cache.ContainsKey(Tuple.Create(new int[] { 1 }, 1))); // This fails
我已经使用 Tuple<int, int>
对其进行了测试它似乎工作正常,但就我而言,我真的需要某种 Tuple<int[], int>
使用那种类型的 key ,它不起作用。
还有其他可行的替代方法吗?
最佳答案
数组不可比较。例如:
var array1 = new int[] { 1 };
var array2 = new int[] { 1 };
Debug.WriteLine(array1 == array2); // this returns false
Debug.WriteLine(Object.Equals(array1, array2)) // this returns false
您需要做以下两件事之一:
1) 替换int[]
使用实现必要 Equals
的自定义类和 GetHashCode
覆盖。
2) 编写一个实现 IEqualityComparer<Tuple<int[], int>>
的类.该类将提供 Equals
和 GetHashCode
Tuple<int[], int>
的方法秒。向您的 Dictionary<Tuple<int[], int>, object>
提供该类的一个实例
关于c# - 字典键不能用作 Tuple<int[], int> 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22721796/