c# - 如何为字符串生成唯一的哈希码

标签 c#

是否有任何函数可以为同一字符串提供相同的哈希码?

我在创建 2 个不同的字符串(但内容相同)时遇到了问题,它们的哈希码不同,因此未在 Dictionary 中正确使用。

我想知道当键是字符串时 Dictionary 使用什么 GetHashCode() 函数。

我正在这样构建我的:

public override int GetHashCode()
{
   String str = "Equip" + Equipment.ToString() + "Destiny" + Destiny.ToString();
   return str.GetHashCode();
}

但它会为使用此代码的每个实例产生不同的结果,尽管字符串的内容相同。

最佳答案

您的标题要求一件事(唯一哈希码),您的 body 要求不同的东西(一致哈希码)。

您声称:

I'm having trouble when creating 2 different strings (but with the same content), their hashcode is different and therefore is not correctly used in a Dictionary.

如果字符串确实具有相同的内容,那根本就不会发生。您的诊断不知何故是错误的。检查字符串中的不可打印字符,例如尾随的 Unicode“空”字符:

string text1 = "Hello";
string text2 = "Hello\0";

此处 text1text2 在某些情况下可能以相同的方式打印,但我希望它们具有不同的哈希码。

请注意,散列码保证是唯一的,不能...只有 232 个可能的散列码从 GetHashCode 返回,但可能有超过 232 个不同的字符串。

另请注意,相同的内容保证在不同的运行中产生相同的哈希码,即使是相同的可执行文件 - 你不应该坚持哈希码任何地方。例如,我相信 32 位 .NET 4 和 64 位 .NET 4 CLR 会为字符串生成不同的哈希码。但是,您声称值未正确存储在 Dictionary 中表明这是在单个进程中 - 一切应该是一致的。

如评论中所述,您完全有可能错误地覆盖了 Equals。我还建议您构建哈希码的方法不是很好。我们不知道 EquipmentDestiny 的类型是什么,但我建议您应该使用如下内容:

public override int GetHashCode()
{
    int hash = 23;
    hash = hash * 31 + Equipment.GetHashCode();
    hash = hash * 31 + Destiny.GetHashCode();
    return hash;
}

这是我通常用于哈希码的方法。 Equals 看起来像这样:

public override bool Equals(object other)
{
    // Reference equality check
    if (this == other)
    {
        return true;
    }         
    if (other == null)
    {
        return false;
    }
    // Details of this might change depending on your situation; we'd
    // need more information
    if (other.GetType() != GetType())
    {
        return false;
    }

    // Adjust for your type...
    Foo otherFoo = (Foo) other;

    // You may want to change the equality used here based on the
    // types of Equipment and Destiny
    return this.Destiny == otherFoo.Destiny &&
           this.Equipment == otherFoo.Equipment;
}

关于c# - 如何为字符串生成唯一的哈希码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8924997/

相关文章:

c# - GCM 服务器在 C# 中向 android 推送通知

c# - 如何定期合并可观察对象?

c# - Win Forms UserControl 未检测到按键

c# - WPF 组合框对更改不具有约束力

c# - 国际奥委会 : How to create objects dynamically

c# - 如何将我的 linux (cntose) 服务器上的 ASP.NET MVC 网站主机或该网站代码转换为 ASP.NET Core

c# - EF Core 3.1 中的时间跨度问题

c# - 在 WPF 中处理来自 Winforms 组件的未处理异常

c# - SQL 2005 随机连接超时/关于数据库超时的最佳实践

c# - 在 WebBrowser 控件中全屏播放 youtube