64 位 .NET 4.5 CLR 上的 32 位 GetHashCode()

本文关键字:GetHashCode 上的 CLR NET | 更新日期: 2023-09-27 17:55:48

在 64 位 .NET 4.5 平台上,是否可以在 32 位 .NET 4.5 平台上计算字符串的 GetHashCode() 方法的结果?

很明显,这不是一个好主意。这里和这里已经问过和解释过这个问题。只有说明如何做到这一点的答案才会被接受。

64 位 .NET 4.5 CLR 上的 32 位 GetHashCode()

GetHashCode()不是

32 位或 64 位特定的,因此在 32 位系统上调用它与在 64 位系统上调用它相同。

您似乎正在尝试出于某种序列化目的重用哈希代码。你不能可靠地做到这一点。如果它更容易,请将字符串的GetHashCode()函数视为如下。

static Dictionary <string, int> HashCodes = new Dictionary<string, int>();
static Random Rand = new Random();
static int PsudoGetHashCode(string stringInQuestion)
{
    lock(HashCodes)
    {
        int result;
        if(!HashCodes.TryGetValue(stringInQuestion, out result)
        {
            result = Rand.Next();
            HashCodes[stringInQuestion] = result;
        }
        return result;
    }
}

您只能保证每次运行程序才能获得相同字符串的相同GetHashCode()值,如果您关闭程序并重新打开它,您很可能会获得一个新值。

唯一

能为你提供可靠结果的解决方案是修复数据库的设计,使其不存储来自 .NET 的内置GetHashCode()