C# 支援運算子多載(Java 不支援),語法:public static 回傳型別 operator 運算子(參數)。
using System;
public class complex
{
private float real, img;
public complex(float p, float q) { real = p; img = q; }
public complex() { real = 0; img = 0; }
public void Print() => Console.WriteLine("{0} + {1}i", real, img);
// 多載 +
public static complex operator +(complex lhs, complex rhs)
{
complex sum = new complex();
sum.real = lhs.real + rhs.real;
sum.img = lhs.img + rhs.img;
return sum;
}
// 多載 -
public static complex operator -(complex lhs, complex rhs)
{
complex result = new complex();
result.real = lhs.real - rhs.real;
result.img = lhs.img - rhs.img;
return result;
}
}
using System;
public class ComplexClass
{
public static void Main(string[] args)
{
complex A = new complex(10.5f, 12.5f);
complex B = new complex(8.0f, 4.5f);
complex C;
Console.Write("Complex Number A: "); A.Print();
Console.Write("Complex Number B: "); B.Print();
C = A + B; Console.Write("\nA + B = "); C.Print();
C = A - B; Console.Write("A - B = "); C.Print();
}
}
輸出:
Complex Number A: 10.5 + 12.5i
Complex Number B: 8 + 4.5i
A + B = 18.5 + 17i
A - B = 2.5 + 8i
+ - ! ~ ++ -- true false+ - * / % & | ^ << >> == != > < >= <=注意: 多載 == 必須同時多載 !=。
System.Exception:所有例外基類System.SystemException:CLR 系統錯誤(IndexOutOfRangeException、NullReferenceException、ArithmeticException、FormatException)System.ApplicationException:使用者自訂例外基類