1. 程式人生 > 其它 >.NetCore中獲取持久化雜湊值

.NetCore中獲取持久化雜湊值

.NET Core中每次程式啟動通過系統內建的 GetHashCode 獲取到的都不同,可通過下面的演算法獲取到的雜湊值持久化不變。

var str = "1";
            Console.WriteLine(str.GetHashCode());
            var str2 = "1";
            Console.WriteLine(str2.GetHashCode());
            Console.WriteLine("-------------------------------");

            var str3 = "
2"; Console.WriteLine(str3.GetExtHashCode()); var str4 = "2"; Console.WriteLine(str4.GetExtHashCode()); Console.ReadKey();
   public static class HashExtends
    {
        public static int GetExtHashCode(this string str)
        {
            unchecked
{ int hash1 = (5381 << 16) + 5381; int hash2 = hash1; for (int i = 0; i < str.Length; i += 2) { hash1 = ((hash1 << 5) + hash1) ^ str[i]; if (i == str.Length - 1)
break; hash2 = ((hash2 << 5) + hash2) ^ str[i + 1]; } return hash1 + (hash2 * 1566083941); } } }

支援作者原創來源:https://codedefault.com/p/why-is-string-gethashcode-method-get-difference-hash-code-when-restart-aspnet-core-application