GetHashCode方法是如何为c#中的值类型工作的
本文关键字:类型 工作 方法 GetHashCode | 更新日期: 2023-09-27 18:01:51
对于整数具有相同的值,但它被强制转换为不同的整数类型的情况,我能期望相同的哈希码吗?
对于浮点数呢?
在某些情况下,对于一对相同的值,从一种类型转换为另一种类型的整数将返回相同的哈希码,但是这种行为不应该依赖。
对于浮点数和双精度数同时表示的一对值,其值将(总是?)不同。
从微软源代码页:http://referencesource.microsoft.com/
UInt16。GetHashCode方法:
internal ushort m_value;
// Returns a HashCode for the UInt16
public override int GetHashCode() {
return (int)m_value;
}
Int16。GetHashCode方法:
internal short m_value;
// Returns a HashCode for the Int16
public override int GetHashCode() {
return ((int)((ushort)m_value) | (((int)m_value) << 16));
}
UInt32。GetHashCode方法:
internal uint m_value;
public override int GetHashCode() {
return ((int) m_value);
}
Int32。GetHashCode方法:
internal int m_value;
public override int GetHashCode() {
return m_value;
}
Int64。GetHashCode方法:
internal long m_value;
// The value of the lower 32 bits XORed with the uppper 32 bits.
public override int GetHashCode() {
return (unchecked((int)((long)m_value)) ^ (int)(m_value >> 32));
}
UInt64。GetHashCode方法
internal ulong m_value;
// The value of the lower 32 bits XORed with the uppper 32 bits.
public override int GetHashCode() {
return ((int)m_value) ^ (int)(m_value >> 32);
}
翻倍。GetHashCode方法
internal double m_value;
//The hashcode for a double is the absolute value of the integer representation
//of that double.
//
[System.Security.SecuritySafeCritical]
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));
}
单身。GetHashCode方法
internal float m_value;
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe override int GetHashCode() {
float f = m_value;
if (f == 0) {
// Ensure that 0 and -0 have the same hash code
return 0;
}
int v = *(int*)(&f);
return v;
}