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

本文详细介绍了C#中如何使用Operator关键字定义静态方法来重载运算符,包括一元、二元运算符及比较运算符等,并提供了具体实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文转自:http://blog.youkuaiyun.com/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
这些运算符无法进行重载。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值