【发布时间】:2010-11-04 09:43:57
【问题描述】:
我正在尝试了解接口IEqualityComparer的GetHashCode方法的作用。
以下示例取自 MSDN:
using System;
using System.Collections.Generic;
class Example {
static void Main() {
try {
BoxEqualityComparer boxEqC = new BoxEqualityComparer();
Dictionary<Box, String> boxes = new Dictionary<Box,
string>(boxEqC);
Box redBox = new Box(4, 3, 4);
Box blueBox = new Box(4, 3, 4);
boxes.Add(redBox, "red");
boxes.Add(blueBox, "blue");
Console.WriteLine(redBox.GetHashCode());
Console.WriteLine(blueBox.GetHashCode());
}
catch (ArgumentException argEx) {
Console.WriteLine(argEx.Message);
}
}
}
public class Box {
public Box(int h, int l, int w) {
this.Height = h;
this.Length = l;
this.Width = w;
}
public int Height { get; set; }
public int Length { get; set; }
public int Width { get; set; }
}
class BoxEqualityComparer : IEqualityComparer<Box> {
public bool Equals(Box b1, Box b2) {
if (b1.Height == b2.Height & b1.Length == b2.Length
& b1.Width == b2.Width) {
return true;
}
else {
return false;
}
}
public int GetHashCode(Box bx) {
int hCode = bx.Height ^ bx.Length ^ bx.Width;
return hCode.GetHashCode();
}
}
Equals 方法实现不应该足以比较两个 Box 对象吗?这就是我们告诉框架用于比较对象的规则的地方。为什么需要 GetHashCode?p>
谢谢。
卢锡安
【问题讨论】:
-
阅读一下:en.wikipedia.org/wiki/Hash_table,然后看看你是否更了解 GetHashCode 的用途。
-
看到这个很好的答案:stackoverflow.com/a/3719802/136967
标签: c# .net gethashcode iequalitycomparer