operator关键字是用来重载内置运算符,或提供类或结构声明中的用户自定义转换
1.重载运算符:
运算符 | 可重载性 |
+、-、!、~、++、--、true、false | 可以重载这些一元运算符, true和false运算符必须成对重载 |
+、-、*、/、%、&、|、^、<<、>> | 可以重载这些二元运算符 |
==、!=、<、>、<=、>= |
可以重载比较运算符,必须成对重载 |
&&、|| | 不能重载条件逻辑运算符,但可以使用能够重载的&和|进行计算 |
[] | 不能重载数组索引运算符,但可以定义索引器 |
() | 不能重载转换运算符,但可以定义新的转换运算符(请参见 explicit 和 implicit) |
+=、-=、*=、/=、%=、&=、|=、^=、<<=、>>= | 不能显式重载赋值运算符,在重写单个运算符如+、-、%时,它们会被 隐式重写 |
=、.、?:、->、new、is、sizeof、typeof | 不能重载这些运算符 |
public static result-type operator unary-operator ( op-type operand )
public static result-type operator binary-operator ( op-type operand, op-type2 operand2 )
注意:需public修饰的静态方法
运算符只能采用值参数,不能采用ref或out参数
op-type 和 op-type2 中至少有一个必须是封闭类型(即运算符所属的类型,或理解为自定义的类型)
2.用户自定义转换
public static implicit operator conv-type-out ( conv-type-in operand )隐式转换
public static explicit operator conv-type-out ( conv-type-in operand )显示转换
class Fraction
{
int num, den;
public Fraction(int num, int den)
{
this.num = num;
this.den = den;
}
//overload operator +
public static Fraction operator +(Fraction a, Fraction b)
{
return new Fraction(a.num * b.den + b.num * a.den, a.den * b.den);
}
//overload operator *
public static Fraction operator *(Fraction a, Fraction b)
{
return new Fraction(a.num * b.num, a.den * b.den);
}
//user-defined conversion from Fraction to double
public static implict operator double(Fraction f)
{
return (double)f.num / f.den;
}
}
class Test
{
static void Main()
{
Fraction a = new Fraction(1, 2);
Fraction b = new Fraction(3, 7);
Fraction c = new Fraction(2, 3);
Console.WriteLine((a * b) + c);
}
}