C#的Hashset包含非唯一对象 [英] C# Hashset Contains Non-Unique Objects
问题描述
使用这个类
public class Foo
{
public string c1, c2;
public Foo(string one, string two)
{
c1 = one;
c2 = two;
}
public override int GetHashCode()
{
return (c1 + c2).GetHashCode();
}
}
和这个HashSet的
And this HashSet
HashSet<Foo> aFoos = new HashSet<Foo>();
Foo aFoo = new Foo("a", "b");
aFoos.Add(aFoo);
aFoos.Add(new Foo("a", "b"));
label1.Text = aFoos.Count().ToString();
我得到的答案2,当它肯定应该是1。有没有办法这么解决这个问题我的HashSet只包含独特的对象?
I get the answer 2, when surely it should be 1. Is there a way to fix this so my HashSet contains only unique objects?
谢谢,灰分
推荐答案
在的HashSet< T>
键入ultamitely使用的平等来判断两个对象是否相等或没有。在键入富
您只覆盖的GetHashCode
,而不是平等。这意味着平等检查将默认回的Object.Equals
它使用引用相等。这就解释了为什么你看到的 HashSet的<多个项目;富>
。
The HashSet<T>
type ultamitely uses equality to determine whether 2 objects are equal or not. In the type Foo
you have only overridden GetHashCode
and not equality. This means equality checks will default back to Object.Equals
which uses reference equality. This explains why you see multiple items in the HashSet<Foo>
.
要解决这个问题,你需要重写等于
在富$ C 。$ C>键入
To fix this you will need to override Equals
in the Foo
type.
public override bool Equals(object obj) {
var other = obj as Foo;
if (other == null) {
return false;
}
return c1 == other.c1 && c2 == other.c2;
}
这篇关于C#的Hashset包含非唯一对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!