What's wrong with defining operator == but not defining Equals() or GetHashCode()?

前端 未结 8 1254
逝去的感伤
逝去的感伤 2020-12-10 01:34

For the code below

public struct Person
{
    public int ID;
    public static bool operator ==(Person a, Person b) { return  a.Equals(b); }
    public stati         


        
相关标签:
8条回答
  • 2020-12-10 02:02
    public struct Coord
    {
        public int x;
        public int y;
    
        public Coord(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    
        public static bool operator ==(Coord c1, Coord c2)
        {
            return c1.x == c2.x && c1.y == c2.y;
        }
    
        public static bool operator !=(Coord c1, Coord c2)
        {
            return !(c1 == c2);
        }
    
        public bool Equals(Coord other)
        {
            return x == other.x && y == other.y;
        }
    
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            return obj is Coord && Equals((Coord) obj);
        }
    
        public override int GetHashCode()
        {
            return 0;
        }
    }
    

    Here's an example. Hopefully, it's helpful.

    0 讨论(0)
  • 2020-12-10 02:03

    My guess is your are getting these warning because compiler doesn't know that you use Equals in == method

    Suppose you have this implementation

    public struct  Person
    {
        public int ID;
        public static bool operator ==(Person a, Person b) { return Math.Abs(a.ID - b.ID) <= 5; }
        public static bool operator !=(Person a, Person b) { return Math.Abs(a.ID - b.ID) > 5; }
    }
    

    Then

     Person p1 = new Person() { ID = 1 };
     Person p2 = new Person() { ID = 4 };
    
     bool b1 = p1 == p2;
     bool b2 = p1.Equals(p2);
    

    b1 would be true, but b2 false

    --EDIT--

    Now suppose you want to do this

    Dictionary<Person, Person> dict = new Dictionary<Person, Person>();
    dict.Add(p1, p1);
    var x1 = dict[p2]; //Since p2 is supposed to be equal to p1 (according to `==`), this should return p1
    

    But this would throw an exception something like KeyNotFound

    But if you add

    public override bool Equals(object obj)
    {
        return Math.Abs(ID - ((Person)obj).ID) <= 5; 
    }
    public override int GetHashCode()
    {
        return 0;
    }
    

    you will get what you want.

    The compiler just warns you that you can face with similar conditions

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