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

Rag*_*ock 8 c#

有没有任何函数,它为同一个字符串提供相同的哈希码?

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

我想知道当键是字符串时使用什么GetHashCode()功能Dictionary.

我正在这样建造我的:

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

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

Jon*_*eet 14

你的标题要求一件事(唯一的哈希码)你的身体要求不同的东西(一致的哈希码).

你声称:

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

如果字符串真的具有相同的内容,那就不会发生.你的诊断错误了.检查字符串中的不可打印字符,例如尾随Unicode"null"字符:

string text1 = "Hello";
string text2 = "Hello\0";
Run Code Online (Sandbox Code Playgroud)

在这里text1并且text2可以在某些上下文中以相同的方式打印,但我希望它们具有不同的哈希码.

请注意,哈希码保证是唯一的,并且不能 ......只返回2 32个可能的哈希码GetHashCode,但是超过2 32个可能的不同字符串.

另请注意,相同的内容不能保证在不同的运行中生成相同的哈希代码,即使是相同的可执行文件 - 您不应该在任何地方持久化哈希代码.例如,我相信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;
}
Run Code Online (Sandbox Code Playgroud)

这是我通常用于哈希码的方法.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;
}
Run Code Online (Sandbox Code Playgroud)