C# String.getHashCode() 为不同的字符串返回相同的值

C# String.getHashCode() returning same value for different strings

我的应用程序 运行 作为 windows 服务,我将 VS2013 附加到它的调试过程。我正在获取图像文件内容的哈希码,以使用以下方法检查差异(在静态 class 中):

static class FileUtils
{
    public static int GetFileHash(string filePath)
    {
        int hash = 0;
        Logger.WriteLog(ToolTipIcon.Info, "Calculating hash code for {0}", filePath);
        StreamReader sr = new StreamReader(filePath, Encoding.Unicode);
        hash = sr.ReadToEnd().GetHashCode();
        sr.Close();
        return hash;
    }
}

在生产环境中运行良好。但是,对于两个不同的图像,此方法将始终 return 2074746262。我试图用相同的代码和图像在 winforms 应用程序中重现这一点,但我做不到。在 VS2013 中调试进程是否会导致此行为?我已经用完全不同的图像替换了其中一张图像,但它仍然发生。

使用GetHasCode检查唯一性永远行不通,不能保证每个不同的对象都会给出不同的哈希码。

Documentation explicitly calls this out。不要依赖 String.GetHashCode 是唯一的。你的假设是错误的。

If two string objects are equal, the GetHashCode method returns identical values. However, there is not a unique hash code value for each unique string value. Different strings can return the same hash code.

首先,您应该意识到您使用 GetHashCode 不正确,原因有两个:

  1. 哈希码不是唯一的,只是分布得很好。哈希码的数量是有限的,而二进制字符串的数量是无限的,因此在物理上不可能为每个字符串生成唯一的哈希码。

  2. 散列码算法的详细信息未明确记录,更改,原因与您似乎无关。特别是,这不是我第一次看到它报告 string.GetHashCode() 在调试器下 运行ning 时改变行为:

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


话虽如此,三个 不同的二进制字符串在相同的 运行 时间环境中散列不同似乎有点不寻常,这取决于附加调试器.除了通常不像你那样信任 GetHashCode 之外,我的下一个猜测是你没有散列你认为你正在散列的东西。在散列之前,我会将二进制数据本身转储到磁盘,并确认您确实有不同的二进制字符串。

而不是 GetHashCode,这绝对不会在所有图像中都是唯一的。按照此 link 使用 MD5 或类似方法:

https://msdn.microsoft.com/en-us/library/s02tk69a%28v=vs.110%29.aspx