我有一种情况,我需要一个这种类型的密钥字典,但它似乎没有找到等效的密钥.
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
Run Code Online (Sandbox Code Playgroud)
我已经通过使用a来测试它Tuple<int, int>,它似乎工作得很好,但在我的情况下,我真的需要某种Tuple<int[], int>类型的键,它不起作用.
还有其他替代方案吗?
数组无法比较.例如:
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
Run Code Online (Sandbox Code Playgroud)
你需要做两件事之一:
1)替换int[]为实现必要Equals和GetHashCode覆盖的自定义类.
2)写一个实现的类IEqualityComparer<Tuple<int[], int>>.该课程将为s 提供Equals和GetHashCode方法Tuple<int[], int>.为您提供该类的实例Dictionary<Tuple<int[], int>, object>