Operator overloading ==, !=, Equals

前端 未结 4 666
醉话见心
醉话见心 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:38

    In fact, this is a "how to" subject. So, here is the reference implementation:

        public class BOX
        {
            double height, length, breadth;
    
            public static bool operator == (BOX b1, BOX b2)
            {
                if ((object)b1 == null)
                    return (object)b2 == null;
    
                return b1.Equals(b2);
            }
    
            public static bool operator != (BOX b1, BOX b2)
            {
                return !(b1 == b2);
            }
    
            public override bool Equals(object obj)
            {
                if (obj == null || GetType() != obj.GetType())
                    return false;
    
                var b2 = (BOX)obj;
                return (length == b2.length && breadth == b2.breadth && height == b2.height);
            }
    
            public override int GetHashCode()
            {
                return height.GetHashCode() ^ length.GetHashCode() ^ breadth.GetHashCode();
            }
        }
    

    REF: https://msdn.microsoft.com/en-us/library/336aedhh(v=vs.100).aspx#Examples

    UPDATE: the cast to (object) in the operator == implementation is important, otherwise, it would re-execute the operator == overload, leading to a stackoverflow. Credits to @grek40.

    This (object) cast trick is from Microsoft String == implementaiton. SRC: https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/string.cs#L643

提交回复
热议问题