c# - string.GetHashCode() 在调试和发布中返回不同的值,如何避免这种情况?

标签 c# string debugging release gethashcode

令我惊讶的是,以下方法在调试和发布中产生了不同的结果:

int result = "test".GetHashCode();

有什么办法可以避免这种情况吗?

我需要一种可靠的方法来对字符串进行哈希处理,并且我需要该值在调试和 Release模式下保持一致。如果可能,我想避免编写自己的哈希函数。

为什么会这样?

仅供引用,反射器给我:

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail), SecuritySafeCritical]
public override unsafe int GetHashCode()
{
    fixed (char* str = ((char*) this))
    {
        char* chPtr = str;
        int num = 0x15051505;
        int num2 = num;
        int* numPtr = (int*) chPtr;
        for (int i = this.Length; i > 0; i -= 4)
        {
            num = (((num << 5) + num) + (num >> 0x1b)) ^ numPtr[0];
            if (i <= 2)
            {
                break;
            }
            num2 = (((num2 << 5) + num2) + (num2 >> 0x1b)) ^ numPtr[1];
            numPtr += 2;
        }
        return (num + (num2 * 0x5d588b65));
    }
}

最佳答案

GetHashCode() 不是您应该用来散列字符串的方法,几乎​​ 100% 的时候都是这样。在不知道自己在做什么的情况下,我建议您使用实际的哈希算法,例如 SHA-1:

using(System.Security.Cryptography.SHA1Managed hp = new System.Security.Cryptography.SHA1Managed()) {
    // Use hp.ComputeHash(System.Text.Encoding.ASCII (or Unicode, UTF8, UTF16, or UTF32 or something...).GetBytes(theString) to compute the hash code.
}

更新:对于更快一点的东西,还有 SHA1Cng,它比 SHA1Managed 快得多。

关于c# - string.GetHashCode() 在调试和发布中返回不同的值,如何避免这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7534169/

相关文章:

c# - Html.ActionLink<> 智能感知问题

c# - 将锯齿状数组转换为列表

C - 字符串数组(二维数组)和内存分配给我带来了不需要的字符

java - 将二维数组写入字符串,然后写入 .txt 文件 - Java

安卓调试?

c# - 用户安装软件时自动安装依赖项(.Net)

c# - 在这种情况下,什么可以解释使用 const 的开销?

string - 在 Julia 中,如何拒绝具有特定字符的单词?

visual-studio - VS10 调试器错误 : Test host process exited unexpectedly

c++ - 如何分析/跟踪已编译的 C++ 应用程序