C# Hashset Contains Non-Unique Objects

前端 未结 3 1230
不思量自难忘°
不思量自难忘° 2020-12-15 21:10

Using this class

public class Foo
{
    public string c1, c2;

    public Foo(string one, string two)
    {
        c1 = one;
        c2 = two;
    }

    pu         


        
相关标签:
3条回答
  • 2020-12-15 21:33

    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>.

    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;
    }
    
    0 讨论(0)
  • 2020-12-15 21:43

    You need to override the equals method as well. The reason for this is that the hashcode is allowed to collide for two objects that is not equal. Otherwise it won't work.

    public override bool Equals(Object obj)
    { 
       Foo otherObject = obj as Foo;
       return otherObject != null && otherObject.c1 == this.c1 && otherObject.c2 == this.c2;
    }
    
    0 讨论(0)
  • 2020-12-15 21:47

    You need to override Equals method. Only GetHashCode is not enough.

    0 讨论(0)
提交回复
热议问题