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

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

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

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

我正在这样建造我的:

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

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

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

你声称:

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

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

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

text1text2在某些上下文中可能会以相同的方式打印,但我希望它们有不同的哈希码。

请注意,哈希码不能保证是唯一的, 并且不能 ……从GetHashCode返回只有2 32个可能的哈希码,但是超过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; } 

这是我通常用于哈希码的方法。 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; }