operator 关键字用于在类或结构声明中声明运算符。运算符声明可以采用下列四种形式之一:
|
---|
public static result-type operator unary-operator ( op-type operand )
public static result-type operator binary-operator (
op-type operand,
op-type2 operand2
)
public static implicit operator conv-type-out ( conv-type-in operand )
public static explicit operator conv-type-out ( conv-type-in operand ) |
参数
-
result-type
-
运算符的结果类型。
-
unary-operator
-
下列运算符之一:+ - ! ~ ++ — true false
-
op-type
-
第一个(或唯一一个)参数的类型。
-
operand
-
第一个(或唯一一个)参数的名称。
-
binary-operator
-
其中一个:+ - * / % & | ^ << >> == != > < >= <=
-
op-type2
-
第二个参数的类型。
-
operand2
-
第二个参数的名称。
-
conv-type-out
-
类型转换运算符的目标类型。
-
conv-type-in
-
类型转换运算符的输入类型。
备注
示例
以下是一个有理数的极其简化的类。该类重载 + 和 * 运算符以执行小数加法和乘法,同时提供将小数转换为双精度的运算符。
| 复制代码 |
---|
// cs_keyword_operator.cs
using System;
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);
}
// define operator double
public static implicit 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((double)(a * b + c));
}
} |
输出
C# 语言规范
有关更多信息,请参见 C# 语言规范中的以下各章节:
-
7.2.2 运算符重载
-
7.2.3 一元运算符重载决策
-
7.2.4 二元运算符重载决策
请参见