你的标题要求一件事(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;
}