代码改变世界

C#运算符重载

2010-02-27 10:46  杨延成  阅读(2154)  评论(2编辑  收藏  举报

运算符重载的关键是在类实例上不能总是调用方法或属性,有时还需要做一些其他的工作,例如对数值进行相加、相乘或逻辑操作,如比较对象等。
在许多情况下,重载运算符允许生成可读性更高、更直观的代码。

 

 

代码
1 public class OperOverLoad
2 {
3
4 /// <summary>
5 /// 测试方法
6 /// </summary>
7   public void TestMethod()
8 {
9 MyPoint my = new MyPoint(31, 5);
10 MyPoint you = new MyPoint(3, 5);
11
12 MyPoint third = my + you;
13
14 Console.WriteLine(third.X);
15
16
17 Console.WriteLine(my == you);
18
19 Console.WriteLine(my.Equals(you));
20 }
21
22 }
23 public class MyPoint
24 {
25 public MyPoint()
26 { }
27
28 public MyPoint(int x, int y)
29 {
30 this.X = x;
31 this.Y = y;
32 }
33
34 public int X
35 {
36 set;
37 get;
38 }
39 public int Y
40 {
41 set;
42 get;
43 }
44
45 /**//// <summary>
46 /// 符重载 格式 public static <返回对象类型> operator <操作符> (参数列表)
47 /// </summary>
48 /// <param name="me"></param>
49 /// <param name="you"></param>
50 /// <returns></returns>
51   public static MyPoint operator +(MyPoint me,MyPoint you)
52 {
53 MyPoint newPoint = new MyPoint();
54 newPoint.X = me.X + you.X;
55 newPoint.Y = me.Y + you.Y;
56 return newPoint;
57
58 /**////快速写法
59   //return new MyPoint(me.X + you.X, you.Y + you.Y);
60   }
61
62
63
64 public static bool operator ==(MyPoint lPoint,MyPoint rPoint )
65 {
66 if ((object)lPoint == null || (object)rPoint == null)
67 {
68 return false;
69 }
70
71 return rPoint.X == lPoint.X && rPoint.Y == lPoint.Y;
72 }
73
74 public static bool operator !=(MyPoint lPoint, MyPoint rPoint)
75 {
76 if ((object)lPoint == null || (object)rPoint == null)
77 {
78 return false;
79 }
80
81 return lPoint.X != rPoint.X || lPoint.Y != rPoint.Y;
82 }
83
84
85 public override int GetHashCode()
86 {
87 return this.ToString().GetHashCode();
88 }
89
90 public override bool Equals(object obj)
91 {
92 if(obj==null)
93 return false;
94
95 MyPoint p = obj as MyPoint;
96
97 if (p == null)
98 return false;
99
100 return this.X.Equals(p.X) && this.Y.Equals(p.Y);
101
102 // return this.X == p;
103  
104 }
105
106
107
108 }