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

2024-06-28

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

我在创建 2 个不同的字符串(但内容相同)时遇到麻烦,它们的哈希码不同,因此未在Dictionary.

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

我正在这样构建我的:

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

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


你的标题要求一件事(unique哈希码)你的身体要求不同的东西(持续的哈希码)。

您声称:

我在创建 2 个不同的字符串(但内容相同)时遇到麻烦,它们的哈希码不同,因此在字典中没有正确使用。

如果字符串真诚地具有相同的内容,这根本不会发生。您的诊断在某种程度上是错误的。检查字符串中的不可打印字符,例如尾随 Unicode“空”字符:

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

Here text1 and text2在某些情况下可能会以相同的方式打印,但我希望它们有不同的哈希码。

Note that hash codes are not guaranteed to be unique and can't be... there are only 232 possible hash codes returned from GetHashCode, but more than 232 possible different strings.

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

正如评论中所述,您完全有可能重写Equals错误地。我还建议您构建哈希码的方法并不好。我们不知道有哪些类型Equipment and Destiny是,但我建议你应该使用类似的东西:

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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为字符串生成唯一的哈希码 的相关文章

随机推荐