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 我那想错了