我想重载==和!=,代码如下.但是提示有错:"定义运算符 == 或运算符 !=,但不重写 Object.Equals(object o)";"定义运算符 == 或运算符 !=,但不重写 Object.GetHashCode()".要怎么搞?
public static bool operator ==(Point P1, Point P2)
        {
            if (System.Object.ReferenceEquals(P1 , P2 ))
            {
                return true;
            }
            if (((object)P1  == null) || ((object)P2  == null))
            {
                return false;
            }
            if  (Math.Abs(P1.X - P2.X) < 1 && Math.Abs(P1.Y - P2.Y) < 1 )return true ;
            else return false ;
        }        public static bool operator !=(Point P1, Point P2)
        {
            return !(P1  == P2 );
        }

解决方案 »

  1.   

    class TwoDPoint : System.Object
    {
        public readonly int x, y;    public TwoDPoint(int x, int y)  //constructor
        {
            this.x = x;
            this.y = y;
        }    public override bool Equals(System.Object obj)
        {
            // If parameter is null return false.
            if (obj == null)
            {
                return false;
            }        // If parameter cannot be cast to Point return false.
            TwoDPoint p = obj as TwoDPoint;
            if ((System.Object)p == null)
            {
                return false;
            }        // Return true if the fields match:
            return (x == p.x) && (y == p.y);
        }    public bool Equals(TwoDPoint p)
        {
            // If parameter is null return false:
            if ((object)p == null)
            {
                return false;
            }        // Return true if the fields match:
            return (x == p.x) && (y == p.y);
        }    public override int GetHashCode()
        {
            return x ^ y;
        }
    }
      

  2.   

    参考MSDN:Equals() 和运算符 == 的重写准则(C# 编程指南)
      

  3.   

    不要通过调用从System.Object中继承的Equals()方法的实例版本,来重载比较运算符,如果这么做,在objA是null时计算(objA==objB),这会产生一个异常,因为.NET运行库会试图计算null.Equals(objB)。采用其他方法(如:重写Equals()方法,调用比较运算符)比较安全
      

  4.   

    我主要是想比较两个点是否相同,只要两点在允许范围内就当作相同,针对我的程序,具体要怎么实现?
    或者要怎么重载equal()和GetHashCode()?