我创建了TheKey
类型k1 = {17,1375984}和k2 = {17,1593144}的两种结构。 显然,第二个字段中的指针是不同的。但是两者都得到相同的散列码= 346948941。 预计会看到不同的哈希码。请参阅下面的代码。ValueType.GetHashCode的本地实现如何工作?
struct TheKey
{
public int id;
public string Name;
public TheKey(int id, string name)
{
this.id = id;
Name = name;
}
}
static void Main() {
// assign two different strings to avoid interning
var k1 = new TheKey(17, "abc");
var k2 = new TheKey(17, new string(new[] { 'a', 'b', 'c' }));
Dump(k1); // prints the layout of a structure
Dump(k2);
Console.WriteLine("hash1={0}", k1.GetHashCode());
Console.WriteLine("hash2={0}", k2.GetHashCode());
}
unsafe static void Dump<T>(T s) where T : struct
{
byte[] b = new byte[8];
fixed (byte* pb = &b[0])
{
IntPtr ptr = new IntPtr(pb);
Marshal.StructureToPtr(s, ptr, true);
int* p1 = (int*)(&pb[0]); // first 32 bits
int* p2 = (int*)(&pb[4]);
Console.WriteLine("{0}", *p1);
Console.WriteLine("{0}", *p2);
}
}
输出:
HASH1 = 346948941
HASH2 = 346948941
更多k1.Equals(k2)是真的 – empi 2011-05-08 10:20:22