IEquatable 인터페이스는 두 객체간에 서로 내부 내용이 같은 지 (예: if(a == b))를 비교하기 위해 구현하여 사용한다.
public class Point: IEquatable<Point>
{
private int x;
private int y;
public Point() : this(0, 0) { }
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public int X
{
get { return x; }
set { x = value; }
}
public int Y
{
get { return y; }
set { y = value; }
}
public override int GetHashCode()
{
return x ^ y;
}
public override bool Equals(object obj)
{
if (!(obj is Point))
return false;
return Equals((Point)obj);
}
public bool Equals(Point other)
{
if (this.x != other.x)
return false;
return this.y == other.y;
}
public static bool operator ==(Point p1, Point p2)
{
return p1.Equals(p2);
}
public static bool operator !=(Point p1, Point p2)
{
return !p1.Equals(p2);
}
}
class EqualsTest
{
static void Main(string[] args)
{
Point p1 = new Point();
Point p2 = new Point();
Point p3 = new Point(10, 20);
Point p4 = new Point(30, 40);
if (p1 == p2)
Console.WriteLine(“p1 == p2”);
if (p3 != p4)
Console.WriteLine(“p3 != p4”);
}
}