C# 哈希集包含非唯一对象

标签 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();
    }
}

还有这个哈希集

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 只包含唯一的对象?

谢谢,阿什。

最佳答案

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

要解决此问题,您需要覆盖 EqualsFoo类型。

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

关于C# 哈希集包含非唯一对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4598826/

相关文章:

c# - 如何在数据绑定(bind)项控件中获取项目的下一个兄弟项?

c# - 如何在asp.net C#中实现寻呼机

c# - 如何在 GroupItem 中显示自定义文本?

C# HTML 字符串显示

Java/ Kotlin : Finding the intersection of multiple HashSets by class ID

java - Java集合框架中的Hashtable、HashMap、HashSet、哈希表概念

c# - Unity - 不同的手机尺寸

java - 如何删除 Hashmap 中重复的键值对? - 不只是复​​制键或值

java - 在 HashSet 的 ArrayList 中重新创建 HashSet

c# - 创建服务引用时 WCF HashSet 更改为 int[]