注册 登录
编程论坛 C++教室

c#Equals方法

maoenlong 发布于 2013-04-10 22:20, 475 次点击
using System;

class Point : Object
{
    protected int x, y;

    public Point()
    {
        this.x = 0;
        this.y = 0;
    }

    public Point(int X, int Y)
    {
        this.x = X;
        this.y = Y;
    }

    public override bool Equals(Object obj)
    {
        //Check for null and compare run-time types.
        if (obj== null || GetType() != obj.GetType()) return false;// GetType()得到当前实例的类型
        Point p = (Point)obj;
        return (x == p.x) && (y == p.y);
    }
    //public void Judge(Object obj)
    //{
    //    if (GetType() != obj.GetType())
    //    {
    //        Console.WriteLine("  flag");
    //    }

    //}

    public override int GetHashCode()
    {
        return x ^ y;
    }
}


class Point3D : Point
{
    int z;

    public Point3D(int X, int Y, int Z)
    {
        this.x = X;
        this.y = Y;
        this.z = Z;
    }

    public override bool Equals(Object obj)
    {
        return base.Equals(obj) && z == ((Point3D)obj).z;//子类型可以强制转换成父类型,但是反之不可
    }

    public override int GetHashCode()
    {
        return base.GetHashCode() ^ z;
    }
}

class MyClass
{

    public static void Main()
    {
        Point point2D = new Point(5, 5);
        Point3D point3Da = new Point3D(5, 5, 2);
        Point3D point3Db = new Point3D(5, 5, 2);
      int a =  point2D.GetHashCode();
      int b = point3Da.GetHashCode();
      //point2D.Judge(point3Db);
  
        Console.WriteLine(" {0}",a);
        Console.WriteLine(" {0}", b);
        if (!point2D.Equals(point3Da))
        {
            Console.WriteLine("point2D does not equal point3Da.");
        }
        if (!point3Db.Equals(point2D))
        {
            Console.WriteLine("Likewise, point3Db does not equal point2D.");
        }
        if (point3Da.Equals(point3Db))
        {
            Console.WriteLine("However, point3Da equals point3Db.");
        }
        Console.Read();
    }
}
我没看明白 主函数中第三个if条件语句base.Equals(obj)是true还是false   我想if (obj== null || GetType() != obj.GetType()) return false;应该返回false
                                    而这一句z == ((Point3D)obj)是false   我那想错了
5 回复
#2
peach54602013-04-11 06:50
从哪抄的代码???
#3
maoenlong2013-04-11 19:09
MSDN
#4
fxbszj2013-04-11 20:01
斑竹该把他移到C#那边去
#5
peach54602013-04-11 20:46
我没看明白 主函数中第三个if条件语句base.Equals(obj)是true还是false   我想if (obj== null || GetType() != obj.GetType()) return false;应该返回false
                                    而这一句z == ((Point3D)obj)是false   我那想错了

哪有Base?
#6
邓士林2013-04-11 21:11
第三个if条件语句base.Equals(obj)是true还是false   根本找不到啊!楼主,没有你所说的东西哦!我怎么帮你呢
1