Operator overloading ==, !=, Equals

前端 未结 4 669
醉话见心
醉话见心 2020-12-02 17:58

I\'ve already gone through question

I understand that, it is necessary to implement ==, != and Equals().

publ         


        
4条回答
  •  清歌不尽
    2020-12-02 18:34

    As Selman22 said, you are overriding the default object.Equals method, which accepts an object obj and not a safe compile time type.

    In order for that to happen, make your type implement IEquatable:

    public class Box : IEquatable
    {
        double height, length, breadth;
    
        public static bool operator ==(Box obj1, Box obj2)
        {
            if (ReferenceEquals(obj1, obj2))
            {
                return true;
            }
            if (ReferenceEquals(obj1, null))
            {
                return false;
            }
            if (ReferenceEquals(obj2, null))
            {
                return false;
            }
    
            return obj1.Equals(obj2);
        }
    
        public static bool operator !=(Box obj1, Box obj2)
        {
            return !(obj1 == obj2);
        }
    
        public bool Equals(Box other)
        {
            if (ReferenceEquals(other, null))
            {
                return false;
            }
            if (ReferenceEquals(this, other))
            {
                return true;
            }
    
            return height.Equals(other.height) 
                   && length.Equals(other.length) 
                   && breadth.Equals(other.breadth);
        }
    
        public override bool Equals(object obj)
        {
            return Equals(obj as Box);
        }
    
        public override int GetHashCode()
        {
            unchecked
            {
                int hashCode = height.GetHashCode();
                hashCode = (hashCode * 397) ^ length.GetHashCode();
                hashCode = (hashCode * 397) ^ breadth.GetHashCode();
                return hashCode;
            }
        }
    }
    

    Another thing to note is that you are making a floating point comparison using the equality operator and you might experience a loss of precision.

提交回复
热议问题