为什么
(m=decimal, d=double)
此外,如预期的那样
(f=float)
这在net3.5和net4.0中都是正确的。
据我了解,这些类型的内部位表示非常不同。那么为什么相等的初始化值的decimal和double类型的哈希码相等呢?在计算哈希之前是否进行了某种转换?
我发现
我验证了这段代码返回了期望的值。但是我没有找到
但这与期望的结果不符(它返回了与
17m.GetHashCode() == 17d.GetHashCode()
(m=decimal, d=double)
此外,如预期的那样
17f.GetHashCode() != 17d.GetHashCode()
(f=float)
这在net3.5和net4.0中都是正确的。
据我了解,这些类型的内部位表示非常不同。那么为什么相等的初始化值的decimal和double类型的哈希码相等呢?在计算哈希之前是否进行了某种转换?
我发现
Double.GetHashCode()
的源代码是这样的://The hashcode for a double is the absolute value of the integer representation
//of that double.
//
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe override int GetHashCode() {
double d = m_value;
if (d == 0) {
// Ensure that 0 and -0 have the same hash code
return 0;
}
long value = *(long*)(&d);
return unchecked((int)value) ^ ((int)(value >> 32));
}
我验证了这段代码返回了期望的值。但是我没有找到
Decimal.GetHashCode()
的源代码。我尝试使用方法。public static unsafe int GetHashCode(decimal m_value) {
decimal d = m_value;
if (d == 0) {
// Ensure that 0 and -0 have the same hash code
return 0;
}
int* value = (int*)(&d);
return unchecked(value[0] ^ value[1] ^ value[2] ^ value[3]);
}
但这与期望的结果不符(它返回了与
int
类型对应的哈希值,考虑到十进制的内部布局也是可以预料的)。因此,Decimal.GetHashCode()
的实现目前仍然未知。
17f.GetHashCode() != 17d.GetHashCode()
是预期的结果? - MagnusGetHashCode
函数仅在同一类型内尝试保持唯一性。双精度和单精度浮点数是否生成相同的哈希码并不重要。 - Magnus