请考虑以下代码:
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()
实施之间存在差异?
答案 0 :(得分:-1)
在ushort GetHashCode()中,当这= 10;
“return(int)(ushort)this |(int)this&lt;&lt; 16;”
产生0x0000000a | 0x000a0000 =&gt; 0x000a000a = 655370
在长和ulong “return(int)this ^(int)(this&gt;&gt; 32);” 产生0x0000000a xor 0x00000000 ==&gt; 0x0000000a = 10;
所以我想其中一个“GetHashCode”有错误的实现。