GetHashCode方法如何适用于C#中的值类型?

时间:2015-07-09 20:40:49

标签: c#

对于整数具有相同值但是会转换为其他整数类型的情况,我是否可以期望相同的哈希码?

浮点数怎么样?

1 个答案:

答案 0 :(得分:2)

在某些情况下,对于一对相同的值,从一种类型转换为另一种类型的整数将返回相同的哈希码, 但不应该依赖这种行为。

对于一对值,其中相同的数字表示为float和double,值将(总是?)不同。

从微软源代码页: 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);
}

Double.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));
}

Single.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;
}