C#Hashset包含非唯一对象

Ash*_*Ash 16 c# hashset

使用这个类

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

而这个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();
Run Code Online (Sandbox Code Playgroud)

我得到答案2,肯定它应该是1.有没有办法解决这个问题,所以我的HashSet只包含唯一的对象?

谢谢,阿什.

Jar*_*Par 26

该HashSet<T>类型ultamitely使用平等来确定2个对象是否相等或没有.在类型中,Foo您只有重写GetHashCode而不是相等.这意味着相等性检查将默认返回Object.Equals使用引用相等性.这就解释了为什么你会看到多个项目HashSet<Foo>.

要解决此问题,您需要Equals在Foo类型中覆盖.

public override bool Equals(object obj) { 
  var other = obj as Foo;
  if (other == null) {
    return false;
  }
  return c1 == other.c1 && c2 == other.c2;
}
Run Code Online (Sandbox Code Playgroud)

  • +1因为它是正确的,但可以补充一点,"GetHashCode"返回的哈希允许碰撞不同的值,这就是为什么比较哈希码并不能确保一般的对象相等. (3认同)

Vic*_*din 7

你需要覆盖Equals方法.只是GetHashCode还不够.