RX_*_*_RX 7 .net hashcode primitive-types
请考虑以下代码:
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>();
Run Code Online (Sandbox Code Playgroud)
输出:
Int32: 10
UInt32: 10
Int64: 10
UInt64: 10
Int16: 655370
UInt16: 10
Run Code Online (Sandbox Code Playgroud)
见之间的差异short和ushort?实际上,这些类的源代码是不同的:
// ushort
public override int GetHashCode()
{
return (int) this;
}
// short
public override int GetHashCode()
{
return (int) (ushort) this | (int) this << 16;
}
Run Code Online (Sandbox Code Playgroud)
但与此同时,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);
}
Run Code Online (Sandbox Code Playgroud)
你能解释一下为什么short和ushort实现之间存在差异GetHashCode()?
小智 -1
在 ushort GetHashCode() 中,当 this = 10 时;
“返回(int)(ushort)这个|(int)这个<< 16;”
产生 0x0000000a | 0x000a0000 => 0x000a000a = 655370
在 long 和 ulong 中“ return (int) this ^ (int) (this >> 32);” 产生 0x0000000a 异或 0x00000000 ==> 0x0000000a = 10;
所以我猜“GetHashCode”之一的实现是错误的。