我可能在使用HashSet和HashCode时有所遗漏,但我不知道为什么它不像我想象的那样工作。我有一个对象,其中HashCode被覆盖。我将对象添加到HashSet中,然后更改一个属性(用于计算HashCode),然后我无法删除该对象。
public class Test
{
public string Code { get; set; }
public override int GetHashCode()
{
return (Code==null)?0: Code.GetHashCode();
}
}
public void TestFunction()
{
var test = new Test();
System.Collections.Generic.HashSet<Test> hashSet = new System.Collections.Generic.HashSet<Test>();
hashSet.Add(test);
test.Code = "Change";
hashSet.Remove(test); //this doesn´t remove from the hashset
}
GetHashCode
实现,让 .NET Framework 为你生成它。只有在需要定义某种值等价性时才需要重写它。如果你想使用Code
作为键,则应该使用Dictionary<Code,OtherData>
而不是HashSet<T>
。 - Dainull
与"Change"
不同,这就是为什么HashSet
无法再找到它的原因。Erip Lippert:“指南:GetHashCode返回的整数值不应该改变。理想情况下,可变对象的哈希码应该只从不可变的字段计算出来,因此对象的哈希值在其整个生命周期中都是相同的。” - Tim SchmelterCode
的初始值为null
,导致哈希码为0。如果“Change”的哈希码也恰好是0,那么它就会找到该值。 - Jon Skeet