.net - 对短和 ushort 的 GetHashCode() 的不同实现感到困惑

标签 .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>();

输出:
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/

相关文章:

java - Java 中一维数组的元素必须是原始数据类型吗?

.net - 为什么 SynchronizedCollection<T> 在 System.ServiceModel 程序集中?

java - Java 中 float 的哈希码

.net - 高潮 RA0000 : No types were registered

java - 什么哈希函数更好?

java - 如何确保 hashCode() 与 equals() 一致?

javascript - RxJS:如何包装和观察字符串的变化?

objective-c - 如何将 NSString 转换为 NSNumber

asp.net - 动态初始化 ResourceManager

c# - 在标签之间查找文本并将其与标签一起替换