主要的算術與比較運算子,可以改寫成供你自己的類別與結構使用。這就稱為_運算子多載_。
這篇文章深入討論了語法,以及哪些運算子可以多載、哪些不行。
大多數運算子的形式如下:
static <return type> operaator <operator symbols>(<parameters>);
轉型運算子的形式如下:
static (explicit|implicit) operator <cast-to-type>(<cast-from-type> <parameter name>);
運算子的行為和靜態方法一樣。
語法範例:
struct Point
{
decimal x;
decimal y;
public static bool operator ==(Point pt, Point ptOther)
{
return pt.x == ptOther.x && pt.y == ptOther.y;
}
public static bool operator !=(Point pt, Point ptOther)
{
return !(pt == ptOther);
}
public static Point operator *(Point pt, decimal scale)
{
var ptNew = new Point();
ptNew.x = pt.x * scale;
ptNew.y = pt.y * scale;
return ptNew;
}
public static implicit operator Point((decimal x, decimal y) xy)
{
var pt = new Point();
pt.x = xy.x;
pt.y = xy.y;
return pt;
}
public static explicit operator (decimal x, decimal y)(Point pt)
{
return (pt.x, pt.y);
}
}
實作一個Equals()方法並從==運算子呼叫它,通常很有用。同樣地,若要進行比較,你可以實作IComparable介面。這兩種情況下,你都能一石二鳥,而且還不只兩隻。
請注意,你不能用不屬於標準運算子集合的符號來建立運算子。只有在文件指明可以多載的運算上,你才能使用既有的符號。可以多載的運算子列在這裡。
請注意,當參數的型別不同時,參數的順序就很重要。在上面的範例程式碼中,pt * 10m是合法的運算式,但10m * pt無法編譯。
這份運算子多載文件詳細說明了語法。