运算符重载方便了我们对自定义类型(自定义的类或者结构体)的计算。
运算符重载关键字 operator。
除了这些运算符不支持:x.y、f(x)、new、typeof、default、checked、unchecked、delegate、is、as、=和=>,其他都支持。
如果是一元运算符,那么运算符重载的方法 参数只有一个;如果是二元运算符,其方法参数就是两个,三元就是三个
分别就是操作符所操作的对象了。比如 !MyDefineObject 其参数就是MyDefineObject。
在比如 MyPoint1+MyPoint2 其参数前后分别是 MyPoint1和MyPoint2。
例子如下:
public class MyPoint { private Point m_point; public MyPoint(int x,int y) { m_point = new Point(x,y); } public static MyPoint operator+ (MyPoint pt,MyPoint pt2) { MyPoint ptNew = new MyPoint(pt.m_point.X + pt2.m_point.X, pt.m_point.Y + pt2.m_point.Y); return ptNew; } public static MyPoint operator -(MyPoint pt, MyPoint pt2) { MyPoint ptNew = new MyPoint(pt.m_point.X - pt2.m_point.X, pt.m_point.Y - pt2.m_point.Y); return ptNew; } //隐式转换 public static implicit operator Point (MyPoint pt) { return pt.m_point; } //显示转换 public static explicit operator MyPoint(Point pt) { return new MyPoint(pt.X,pt.Y); } public override string ToString() { return $"[{m_point.X},{m_point.Y}]"; } }
internal class Program { static void Main(string[] args) { MyPoint pt1=new MyPoint(10,10); MyPoint pt2 = new MyPoint(5, 5); MyPoint ptAdd=pt1+ pt2; MyPoint ptMinus = pt1 - pt2; Console.WriteLine(pt1 + "+" + pt2 + "=" + ptAdd); Console.WriteLine(pt1 + "-" + pt2 + "=" + ptMinus); Point pt3 = ptAdd; Point pt4 = new Point(555,555); MyPoint pt5 = (MyPoint)pt4; Console.WriteLine($"pt3=[{pt3.X},{pt3.Y}]"); Console.WriteLine($"pt5={pt5}"); } }