我正在尝试使用int数组作为C#中的键,我看到的行为是意外的(对我而言).
var result = new Dictionary<int[], int>();
result[new [] {1, 1}] = 100;
result[new [] {1, 1}] = 200;
Assert.AreEqual(1, result.Count); // false is 2
Run Code Online (Sandbox Code Playgroud)
它似乎与List相同.
var result = new Dictionary<List<int>, int>();
result[new List<int> { 1, 1 }] = 100;
result[new List<int> { 1, 1 }] = 200;
Assert.AreEqual(1, result.Count); // false is 2
Run Code Online (Sandbox Code Playgroud)
我希望Dictionary能够使用Equals来决定地图中是否存在Key.似乎并非如此.
有人可以解释为什么以及如何让这种行为发挥作用?
.NET列表和数组没有内置的相等比较,因此您需要提供自己的:
class ArrayEqComparer : IEqualityComparer<int[]> {
public static readonly IEqualityComparer<int[]> Instance =
new ArrayEqComparer();
public bool Equals(int[] b1, int[] b2) {
if (b2 == null && b1 == null)
return true;
else if (b1 == null | b2 == null)
return false;
return b1.SequenceEqual(b2);
}
public int GetHashCode(int[] a) {
return a.Aggregate(37, (p, v) => 31*v + p);
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以按如下方式构建字典:
var result = new Dictionary<int[],int>(ArrayEqComparer.Instance);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
126 次 |
| 最近记录: |