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

前端 未结 8 1266
逝去的感伤
逝去的感伤 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: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 dict = new Dictionary();
    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

提交回复
热议问题