| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 475 人关注过本帖
标题:c#Equals方法
取消只看楼主 加入收藏
maoenlong
Rank: 2
等 级:论坛游民
帖 子:10
专家分:15
注 册:2012-6-14
结帖率:100%
收藏
已结贴  问题点数:20 回复次数:1 
c#Equals方法
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   我那想错了
搜索更多相关主题的帖子: false compare Object public 
2013-04-10 22:20
maoenlong
Rank: 2
等 级:论坛游民
帖 子:10
专家分:15
注 册:2012-6-14
收藏
得分:0 
MSDN
2013-04-11 19:09
快速回复:c#Equals方法
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.011890 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved