.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

 

posted @ 2022-05-24 17:12  吉姆杨  阅读(191)  评论(0编辑  收藏  举报