C#Decimal.GetHash code()和Double.GetHash code()等于GetHash、Decimal、Double、code

2023-09-04 07:58:47 作者:kao、孟婆湯沒了

为什么说 17m.GetHash code()== 17d.GetHash code() (M =小数,D =双) 此外,符合市场预期 17f.GetHash code()!= 17d.GetHash code() (F =浮动) 这似乎是真实的为在.net3.5和net4.0。 据我了解,这些类型的内部位重presentations有很大的不同。那么怎么来散列$ C $的十进制和双类型相等等于初始值CS?有一些转换正在发生的哈希计算过吗? 我发现,源$ C ​​$下 Double.GetHash code()是这样的:

Why is it that 17m.GetHashCode() == 17d.GetHashCode() (m=decimal, d=double) Additionally, as expected 17f.GetHashCode() != 17d.GetHashCode() (f=float) This appears to be true for both net3.5 and net4.0. As I understand, the internal bit representations of these types are quite different. So how come that the hash codes of decimal and double types equal for equal initialization values? Is there some conversion taking place before calculation of the hash? I found that the source code for Double.GetHashCode() is this:

//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));  
} 

我验证了这个code的回报期望值。但我没有找到源$ C ​​$下 Decimal.GetHash code()。我尝试使用方法

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 类型,这也有望考虑的

 
精彩推荐
图片推荐