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

前端 未结 8 1271
逝去的感伤
逝去的感伤 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 01:51

    All you need to do is add another member to your struct say Forename.

    So if you has two persons with an ID of 63 but different forenames, are they equal or not?

    All depends on what definition of "same" you want to implement.

    Use a better example struct, write a noddy applictaion to execute the various methods and see what happens when you change the definitions of equality and or equivalence, if they aren't all in step, you end up with things like !(a == b) != (a != b), which might be true, but if you don't override all the methods whoever uses you code will wonder what your intent was.

    Basically the compiler is telling you to be good citizen and make your intent clear.

提交回复
热议问题