string.GetHashCode()在debug vs release中返回不同的值,如何避免这种情况? [英] string.GetHashCode() returns different values in debug vs release, how do I avoid this?
问题描述
int result =test.GetHashCode ();
有什么办法可以避免吗?
我需要一个可靠的方法来排序字符串,我需要该值在调试和释放模式下保持一致。我想避免编写自己的散列函数,如果可能的话。
为什么会这样?
反馈给我:
[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;
(int i = this.Length; i> 0; i - = 4)
{
num =(((num(<< 5)+ num) >> 0x1b))^ numPtr [0];
if(i< = 2)
{
break;
}
num2 =(((num2 <5)+ num2)+(num2>> 0x1b))^ numPtr [1]
numPtr + = 2;
}
return(num +(num2 * 0x5d588b65));
}
}
code> GetHashCode()是不是几乎100%的时间你应该用来哈希字符串。不知道你在做什么,我建议你使用一个实际的哈希算法,如SHA-1:
using .Security.Cryptography.SHA1Managed hp = new System.Security.Cryptography.SHA1Managed()){
//使用hp.ComputeHash(System.Text.Encoding.ASCII(或Unicode,UTF8,UTF16或UTF32或某些东西...)GetBytes(theString)来计算哈希码
}
更新对于某些东西要快一些,还有 SHA1Cng
,明显快于 SHA1Managed
。
To my surprise the folowing method produces a different result in debug vs release:
int result = "test".GetHashCode();
Is there any way to avoid this?
I need a reliable way to hash a string and I need the value to be consistent in debug and release mode. I would like to avoid writing my own hashing function if possible.
Why does this happen?
FYI, reflector gives me:
[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()
is not what you should be using to hash a string, almost 100% of the time. Without knowing what you're doing, I recommend that you use an actual hash algorithm, like 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.
}
Update: For something a little bit faster, there's also SHA1Cng
, which is significantly faster than SHA1Managed
.
这篇关于string.GetHashCode()在debug vs release中返回不同的值,如何避免这种情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!