-
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace CountStrDemo
- {
- class 比較子重載
- {
- public static void Main(string[] args)
- {
- // 比較預算符有6個,3對 分別是:
- // == !=
- // > <
- // >= <=
- //成對重載,例如,重載了 == 則必須重載 != 反回類型必須是bool
- }
- class MyVectorForEq
- {
- public int x;
- public int y;
- public MyVectorForEq( int x , int y )
- {
- this.x = x;
- this.y = y;
- }
- //重載==運算子 同時必須成對重載 !=
- public static bool operator == ( MyVectorForEq lobj , MyVectorForEq robj )
- {
- //這裡只是做了成員值的比較,ms推薦重寫Equals方法與配合hash來進行對象內容的比較
- if (lobj.x == robj.x && lobj.y == robj.y)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- public static bool operator !=( MyVectorForEq lobj , MyVectorForEq robj)
- {
- if (lobj.x == robj.x && lobj.y == robj.y)
- {
- return false;
- }
- else
- {
- return true;
- }
- }
- }
- }
- }
using System;
- using System.Collections.Generic;
- using System.Text;
- namespace CountStrDemo
- {
- class 運算浮重載
- {
- public static void Main(string[] args)
- {
- Vector vec1 = new Vector( 5 , 6 , 7 );
- Vector vec2 = new Vector( 2 , 2 , 2 );
- Vector revec = vec1 + vec2;
- Console.WriteLine( "x={0} y={1} z={2}" , revec.x , revec.y , revec.z );
- Console.Read();
- }
- }
- class Vector
- {
- public int x;
- public int y;
- public int z;
- public Vector( int x , int y , int z )
- {
- this.x = x;
- this.y = y;
- this.z = z;
- }
- public Vector(Vector vec)
- {
- this.x = vec.x;
- this.y = vec.y;
- this.z = vec.z;
- }
- //定義重載 , 和方法類似,不過必須是public static ...可以記做沒有方法名,呵呵operator + 指重載+號運算
- public static Vector operator + ( Vector lvec , Vector rvec )
- {
- Vector revec = new Vector( lvec );
- revec.x += rvec.x;
- revec.y += rvec.y;
- revec.z += rvec.z;
- return revec;
- }
- }
- }
-------------------------------------------------------------------------------------------------