運算子多載:預先定義的一元、算術、相等和比較運算子

使用者定義型別可以多載預先定義的 C# 運算子。 也就是說,如果其中一個或這兩個運算元屬於該型別時,該型別可以提供作業的自訂實作。 可多載運算子一節會說明可多載的 C# 運算子。

使用 operator 關鍵字來宣告運算子。 運算子宣告必須滿足下列規則:

  • 它包含 publicstatic 修飾詞。
  • 一元運算子有一個輸入參數。 二元運算子有兩個輸入參數。 在每個案例中,至少一個參數必須有類型 TT?,其中 T 是包含運算子宣告的類型。

下列範例會定義簡化的結構以表示有理數。 結構會多載一些算術運算子

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 關鍵字定義自訂型別轉換。 如需詳細資訊,請參閱使用者定義轉換運算子

可多載的運算子

下表顯示可以多載的運算子:

操作員 備註
truefalse 運算子必須一起多載。


x << y  },
必須成對多載,如下所示:==!=<><=>=

不可多載的運算子

下表顯示不可多載的運算子:

操作員 替代項目
% 多載 truefalse 運算子及 &| 運算子。 如需詳細資訊,請參閱使用者定義的條件式邏輯運算子
% 定義索引子
(T)x 定義可由轉換運算式執行的自訂型別轉換。 如需詳細資訊,請參閱使用者定義轉換運算子
多載對應的二進位運算子。 例如,當您多載二進位 + 運算子時,+= 會隱含多載。


無。

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格的下列幾節:

另請參閱