运算符重载的关键是在类实例上不能总是调用方法或属性,有时还需要做一些其他的工作,例如对数值进行相加、相乘或逻辑操作,如比较对象等。
在许多情况下,重载运算符允许生成可读性更高、更直观的代码。
- public class OperOverLoad
- {
- /// <summary>
- /// 测试方法
- /// </summary>
- public void TestMethod()
- {
- MyPoint my = new MyPoint(31, 5);
- MyPoint you = new MyPoint(3, 5);
- MyPoint third = my + you;
- Console.WriteLine(third.X);
- Console.WriteLine(my == you);
- Console.WriteLine(my.Equals(you));
- }
- }
- public class MyPoint
- {
- public MyPoint()
- { }
- public MyPoint(int x, int y)
- {
- this.X = x;
- this.Y = y;
- }
- public int X
- {
- set;
- get;
- }
- public int Y
- {
- set;
- get;
- }
- /**//// <summary>
- /// 符重载 格式 public static <返回对象类型> operator <操作符> (参数列表)
- /// </summary>
- /// <param name="me"></param>
- /// <param name="you"></param>
- /// <returns></returns>
- public static MyPoint operator +(MyPoint me,MyPoint you)
- {
- MyPoint newPoint = new MyPoint();
- newPoint.X = me.X + you.X;
- newPoint.Y = me.Y + you.Y;
- return newPoint;
- /**////快速写法
- //return new MyPoint(me.X + you.X, you.Y + you.Y);
- }
- public static bool operator ==(MyPoint lPoint,MyPoint rPoint )
- {
- if ((object)lPoint == null || (object)rPoint == null)
- {
- return false;
- }
- return rPoint.X == lPoint.X && rPoint.Y == lPoint.Y;
- }
- public static bool operator !=(MyPoint lPoint, MyPoint rPoint)
- {
- if ((object)lPoint == null || (object)rPoint == null)
- {
- return false;
- }
- return lPoint.X != rPoint.X || lPoint.Y != rPoint.Y;
- }
- public override int GetHashCode()
- {
- return this.ToString().GetHashCode();
- }
- public override bool Equals(object obj)
- {
- if(obj==null)
- return false;
- MyPoint p = obj as MyPoint;
- if (p == null)
- return false;
- return this.X.Equals(p.X) && this.Y.Equals(p.Y);
- // return this.X == p;
- }