格式:public static 回傳型別 operator 運算子(參數列表)。所有多載皆為 static 方法。若多載 == 必須同時多載 !=。
+ - ! ~ ++ -- true false+ - * / % & | ^ << >> == != > < >= <=
using System;
public class complex
{
private float real;
private float 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;
}
}
此類別示範如何讓自訂型別支援直觀的算術運算子。