
::: info
我平常只會用到 == 去比較 int 或 string,但其實大部分的運算符都可以重載方法符合使用情境
:::
:::danger
重載方法需要用到特定的operator且方法必須要靜態(static)
:::
### 先建立一個Point類別來實作,Equals在之前文章說明過
[C#內建方法Equals](https://hackmd.io/snp33ItkTaS5NdVWFTLtNg)
```
public class Point : IEquatable<Point>
{
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y)
{
X = x;
Y = y;
}
public bool Equals(Point? other)
{
return X==other.X && Y==other.Y;
}
public override bool Equals(object obj)
{
return obj is Point p && Equals(p);
}
}
```
:::info
重載過後就可以直接使用pointA = PointB 或是 PointA+PointB 這些方法了
:::
```
public static Point operator +(Point a, Point b)
{
return new Point(a.X + b.X, a.Y + b.Y);
}
public static bool operator ==(Point a, Point b)
{
return a.Equals(b);
}
public static bool operator !=(Point a, Point b)
{
return !a.Equals(b);
}
```
[更多運算符參考](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading)