你可以让自己定义的类和结构体使用主要的算术运算符和比较运算符。这称为运算符重载。
这篇文章详细讨论了相关语法,以及哪些运算符可以重载、哪些不可以。
大多数运算符的形式如下:
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将无法编译。
这份运算符重载文档详细介绍了相关语法。