C 中常見型別的雜湊碼

GetHashCode() 方法為 System 名稱空間中的內建和常見 C#型別生成的雜湊碼如下所示。

布林

如果值為 true,則為 1,否則為 0。

位元組UInt16Int32UInt32

值(如果需要,則轉換為 Int32)。

為 SByte

((int)m_value ^ (int)m_value << 8);

Char

(int)m_value ^ ((int)m_value << 16);

INT16

((int)((ushort)m_value) ^ (((int)m_value) << 16));

Int64

64 位數的低 32 位和高 32 位之間的 Xor

(unchecked((int)((long)m_value)) ^ (int)(m_value >> 32));

UInt64DateTimeTimeSpan

((int)m_value) ^ (int)(m_value >> 32);

十進位制

((((int *)&dbl)[0]) & 0xFFFFFFF0) ^ ((int *)&dbl)[1];

賓語

RuntimeHelpers.GetHashCode(this);

預設實現是使用同步塊索引

字串

雜湊碼計算取決於平臺型別(Win32 或 Win64),使用隨機字串雜湊,除錯/釋放模式的功能。在 Win64 平臺的情況下:

int hash1 = 5381;
int hash2 = hash1;
int c;
char *s = src;
while ((c = s[0]) != 0) {
    hash1 = ((hash1 << 5) + hash1) ^ c;
    c = s[1];
    if (c == 0)
        break;
    hash2 = ((hash2 << 5) + hash2) ^ c;
    s += 2;
}
return hash1 + (hash2 * 1566083941);

值型別

第一個非靜態欄位是查詢並獲取它的雜湊碼。如果型別沒有非靜態欄位,則返回該型別的雜湊碼。無法獲取靜態成員的雜湊碼,因為如果該成員與原始型別的型別相同,則計算結束於無限迴圈中。

可空<T>

return hasValue ? value.GetHashCode() : 0;

排列

int ret = 0;
for (int i = (Length >= 8 ? Length - 8 : 0); i < Length; i++) 
{
    ret = ((ret << 5) + ret) ^ comparer.GetHashCode(GetValue(i));
}

參考