【C#】运算符重载(operator)
概述
用户定义的类型可重载预定义的 C# 运算符。 也就是说,当一个或两个操作数都是某类型时,此类型可提供操作的自定义实现。
使用 operator 关键字来声明运算符。 运算符声明必须符合以下规则:
- 同时包含 public 和 static 修饰符。
- 一元运算符有一个输入参数。 二元运算符有两个输入参数。 在每种情况下,都至少有一个参数必须具有类型 T 或 T?,其中 T
是包含运算符声明的类型。
可重载运算符
| 运算符 | 说明 |
|---|---|
+x, -x, !x, ~x, ++, --, true, false | true和 false 运算符必须一起重载。 |
x + y, x - y, x * y, x / y, x % y,x & y, x | y, x ^ y,x << y, x >> y, x >>> y | |
x == y, x != y, x < y, x > y, x <= y, x >= y | 必须按如下方式成对重载: == 和 !=、 < 、 ><= 和 >=。 |
不可重载运算符
| 运算符 | 备选方法 |
|---|---|
x && y, x || y | 重载 true 和 false 运算符以及 & 或 | 运算符。 有关详细信息,请参阅用户定义的条件逻辑运算符。 |
a[i], a?[i] | 定义索引器。 |
(T)x | 定义可由强制转换表达式执行的自定义类型转换。 有关详细信息,请参阅用户定义转换运算符。 |
+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>= | 重载相应的二元运算符。 例如,重载二元 + 运算符时, += 将隐式重载。 |
^x, x = y, x.y, x?.y, c ? t : f, x ?? y, ??= y,x..y, x->y, =>, f(x), as, await, checked, unchecked, default, delegate, is, nameof, new,sizeof, stackalloc, switch, typeof, with | 无。 |
示例
下面是分数的一个极其简化的类。该类重载了 + 和 * 运算符,以执行分数加法和乘法;同时提供了将 Fraction 类型转换为 double 类型的转换运算符。
// cs_keyword_operator.cs
using System;
class Fraction
{
int num, den;
public Fraction(int num, int den)
{
this.num = num;
this.den = den;
}
// overload operator +
public static Fraction operator +(Fraction a, Fraction b)
{
return new Fraction(a.num * b.den + b.num * a.den,
a.den * b.den);
}
// overload operator *
public static Fraction operator *(Fraction a, Fraction b)
{
return new Fraction(a.num * b.num, a.den * b.den);
}
// user-defined conversion from Fraction to double
public static implicit operator double(Fraction f)
{
return (double)f.num / f.den;
}
}
class Test
{
static void Main()
{
Fraction a = new Fraction(1, 2);
Fraction b = new Fraction(3, 7);
Fraction c = new Fraction(2, 3);
Console.WriteLine((double)(a * b + c));
}
}
输出:0.880952380952381