How can we check reference equality for a type that implements equality operator?

前端 未结 2 1028
天命终不由人
天命终不由人 2021-01-26 02:12

In C#, how can we check reference equality for a type that implements equality operator?

class C
{
    public int Val{get;set;}
    public static bool operator =         


        
相关标签:
2条回答
  • 2021-01-26 02:49

    If you mean equality by reference, you may use the Object.ReferenceEquals static method even if the == operator was overloaded for the current type to work otherwise:

    Object.ReferenceEquals(obj1, obj2);
    
    0 讨论(0)
  • 2021-01-26 03:13

    What does object "object equality"?

    If by "how can we check object equality for a type that implements equality operator?", you actually mean "how can we check object equality for a type that implements IEquatable<T>", the short answer is...however you want (with some caveats).

    The documentation for IEquatable<T> offers some guidelines. You might also want to implement IComparable<T> as well. And if you implement both IEquatable<T> and IComparable<T>, it would make sense if your Equals() method returns true for all the cases where your CompareTo() method returns 0, and for your Equals() method to return false for all the cases where your CompareTo() method returns a non-zero value.

    Further, you might want to ensure that you properly override == and != to provide the same behaviour as calling Equals().

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