[英]How ToString(), GetHashCode() methods appear for each object in C#
[英]How do the GetHashCode methods work for the value types in C#?
在整數具有相同值但將其強制轉換為其他整數類型的情況下,我是否可以期望使用相同的哈希碼?
浮點數呢?
在某些情況下,對於一對相同的值,從一種類型轉換為另一種類型的整數將返回相同的哈希碼,但是不應依賴此行為。
對於一對值,其中相同的數字分別表示為浮點數和雙精度數,則該值將(總是?)不同。
從Microsoft源代碼頁中: 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.