C#里使用Operator关键字定义静态方法来重载运算符。
例如:
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 | 强制转换运算符无法进行重载。 |
| += -= *= /= %= &= |= ^= <<= >>= | 赋值运算符无法进行重载。 但是它们使用对应的非赋值运算符来计算(例如+=使用了+)。 |
| = . ?: ?? -> => f(x) as is checked unchecked default delegate new sizeof typeof | 这些运算符无法进行重载。 |

本文详细介绍了如何在C#中使用Operator关键字定义静态方法来实现运算符重载,包括一元、二元运算符及比较运算符的重载方式,并强调了必须成对重载的规则。
669

被折叠的 条评论
为什么被折叠?



