使用 operator 关键字来声明运算符。 运算符声明必须符合以下规则:
1.同时包含 public 和 static 修饰符。
2.一元运算符采用一个参数。 二元运算符采用两个参数。 在每种情况下,都至少有一个参数必须具有类型 T 或 T?,其中 T 是包含运算符声明的类型。
using System;
public readonly struct Fraction
{
private readonly int num;
private readonly int den;
public Fraction(int numerator, int denominator)
{
if (denominator == 0)
{
throw new ArgumentException("Denominator cannot be zero.", nameof(denominator));
}
num = numerator;
den = denominator;
}
public static Fraction operator +(Fraction a) => a;
public static Fraction operator -(Fraction a) => new Fraction(-a.num, a.den);
public static Fraction operator +(Fraction a, Fraction b)
=> new Fraction(a.num * b.den + b.num * a.den, a.den * b.den);
public static Fraction operator -(Fraction a, Fraction b)
=> a + (-b);
public static Fraction operator *(Fraction a, Fraction b)
=> new Fraction(a.num * b.num, a.den * b.den);
public static Fraction operator /(Fraction a, Fraction b)
{
if (b.num == 0)
{
throw new DivideByZeroException();
}
return new Fraction(a.num * b.den, a.den * b.num);
}
public override string ToString() => $"{num} / {den}";
}
public static class OperatorOverloading
{
public static void Main()
{
var a = new Fraction(5, 4);
var b = new Fraction(1, 2);
Console.WriteLine(-a); // output: -5 / 4
Console.WriteLine(a + b); // output: 14 / 8
Console.WriteLine(a - b); // output: 6 / 8
Console.WriteLine(a * b); // output: 5 / 8
Console.WriteLine(a / b); // output: 10 / 4
}
}
可以通过定义从 int
到 Fraction
的隐式转换来扩展前面的示例。 然后,重载运算符将支持这两种类型的参数。 也就是说,可以将一个整数添加到一个分数中,得到一个分数结果。
还可以使用 operator
关键字来定义自定义类型转换。
可重载运算符
下表提供了 C# 运算符可重载性的相关信息:
运算符 | 可重载性 |
---|---|
+x、-x、!x、~x、++、--、true、false | 这些一元运算符可以进行重载。 |
这些二元运算符可以进行重载。 某些运算符必须成对重载;有关详细信息,请查看此表后面的备注。 | |
x && y、x || y | 无法重载条件逻辑运算符。 但是,如果具有已重载的 true 和 false 运算符的类型还以某种方式重载了 & 或 | 运算符,则可针对此类型的操作数分别计算 && 或 || 运算符。 有关详细信息,请参阅 C# 语言规范的用户定义条件逻辑运算符部分。 |
a[i] | 元素访问不被视为可重载运算符,但你可定义索引器。 |
(T)x | 强制转换运算符不能重载,但可以定义新的转换运算符。 有关详细信息,请参阅用户定义转换运算符。 |
+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>= | 复合赋值运算符不能显式重载。 但在重载二元运算符时,也会隐式重载相应的复合赋值运算符(若有)。 例如,使用 + (可以进行重载)计算 += 。 |
^x、x = y、x.y、c ? t : f、x ?? y、x ??= y、x..y、x->y、=> | 这些运算符无法进行重载。 |