[C#基础]C#中的重载运算符

来源:互联网 发布:淘宝副总裁 编辑:程序博客网 时间:2024/05/16 10:05

本文转自:http://blog.csdn.net/ecidevilin/article/details/53401006,请点击链接查看原文,尊重楼主版权。


C#里使用Operator关键字定义静态方法来重载运算符:

e.g.

public class TestPoint    {    public TestPoint(int x_, int y_)    {    x = x_;    y = y_;    }    public int x;    public int y;    public static TestPoint operator++ (TestPoint pt)    {    return new TestPoint (pt.x + 1, pt.y + 1);    }    public static TestPoint operator-- (TestPoint pt)    {    return new TestPoint (pt.x - 1, pt.y - 1);    }    public static TestPoint operator+ (TestPoint pt1, TestPoint pt2)    {    return new TestPoint (pt1.x + pt2.x, pt1.y + pt2.y);    }    public static bool operator== (TestPoint pt1, TestPoint pt2)    {    return pt1.x == pt2.x && pt1.y == pt2.y;    }    public static bool operator!= (TestPoint pt1, TestPoint pt2)    {    return !(pt1 == pt2);    }    public override string ToString()    {    return string.Format("{0} , {1}", this.x, this.y);    }    public int this[int idx]    {    get {    if (idx == 0) {    return x;    } else if (idx == 1) {    return y;    } else {    throw new System.IndexOutOfRangeException ();    }    }    set {     if (idx == 0) {    x = value;    } else if (idx == 1) {    y = value;    } else {    throw new System.IndexOutOfRangeException ();    }    }    }    }
使用:

var tp1 = new TestPoint (1, 2);Console.WriteLine (tp1++);Console.WriteLine (++tp1);Console.WriteLine (tp1);var tp2 = new TestPoint (10, 20);Console.WriteLine (tp1 + tp2);tp1 += tp2;Console.WriteLine (tp1);tp1 [1] = 55;Console.WriteLine (tp1);Console.WriteLine (tp2[0]);Console.WriteLine (tp1 != tp2);

+  - 
!  ~ 
++  -- 
true  false
这些一元运算符可以进行重载。+  -  *  /  % 
&  | 

<<  >>
这些二元运算符可以进行重载。==  != 
<  >
<=  >=
比较运算符可以进行重载
如果进行重载,则必须成对进行重载。
即如果重载 
== ,也必须重载!= , 反之亦然。
对于 
< 和 > 以及 <= 和 >= 也是同理。
&&  ||逻辑运算符无法进行重载,但是它们使用 & 和 | 来计算。[]索引运算符无法进行重载。
但是可以定义索引器
(参考C#语法小知识(六)属性与索引器)。
(T)x强制转换运算符无法进行重载。

但是可以使用explicit 和 implicit定义转换运算符。

(参考C#语法小知识(二十四)自定义类型转换)

+=  -=  *=  /=  %= 
&=  |= 
^=
<<=  >>=
赋值运算符无法进行重载。
但是它们使用对应的非赋值运算符来计算(例如+=使用了+)。
=
.
?:  ??
->  =>
f(x)
as  is
checked  unchecked
default
delegate
new  sizeof  typeof
这些运算符无法进行重载。



原创粉丝点击