令我惊讶的是,以下方法在调试和发布中产生了不同的结果:
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/