考虑以下代码:
private static void TestHashCode<T>()
{
dynamic initialValue = 10;
Console.WriteLine("{0}: {1}", typeof(T).Name, ((T)initialValue).GetHashCode());
}
TestHashCode<int>();
TestHashCode<uint>();
TestHashCode<long>();
TestHashCode<ulong>();
TestHashCode<short>();
TestHashCode<ushort>();
输出:
Int32: 10
UInt32: 10
Int64: 10
UInt64: 10
Int16: 655370
UInt16: 10
查看
short
的区别和 ushort
?事实上,这些类的源代码是不同的:// ushort
public override int GetHashCode()
{
return (int) this;
}
// short
public override int GetHashCode()
{
return (int) (ushort) this | (int) this << 16;
}
但与此同时,
GetHashCode()
int
的签名/未签名版本的实现和 long
是相等的:// int and uint
public override int GetHashCode()
{
return (int) this;
}
// long and ulong
public override int GetHashCode()
{
return (int) this ^ (int) (this >> 32);
}
你能解释一下为什么
short
之间有区别吗?和 ushort
GetHashCode()
的实现?
最佳答案
在 ushort GetHashCode() 中,当 this = 10 时;
“返回 (int) (ushort) this | (int) this << 16;”
产生 0x0000000a | 0x000a0000 => 0x000a000a = 655370
在长和乌隆
"返回 (int) this ^ (int) (this >> 32);"
产生 0x0000000a xor 0x00000000 ==> 0x0000000a = 10;
所以我猜“GetHashCode”之一有错误的实现。
关于.net - 对短和 ushort 的 GetHashCode() 的不同实现感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25789668/