【发布时间】:2011-08-21 01:42:45
【问题描述】:
我创建了两个结构 TheKey 类型 k1={17,1375984} 和 k2={17,1593144}。
显然,第二个字段中的指针是不同的。但两者都得到相同的哈希码=346948941。
预计会看到不同的哈希码。请参阅下面的代码。
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);
}
}
输出:
17
1375984
17
1593144
哈希1=346948941
hash2=346948941
【问题讨论】:
-
更何况 k1.Equals(k2) 是真的