string.GetHashCode() returns different values in debug vs release, how do I avoid this?

后端 未结 3 427
眼角桃花
眼角桃花 2020-12-19 07:31

To my surprise the folowing method produces a different result in debug vs release:

int result = \"test\".GetHashCode();

Is there any way t

3条回答
  •  自闭症患者
    2020-12-19 08:22

    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.

提交回复
热议问题