operator关键字用来重载内置运算符,使用方法如下:
public class OperatorController : Controller { // // GET: /Operator/ public int num, den; public OperatorController(int num, int den) { this.num = num; this.den = den; } // overload operator + public static OperatorController operator +(OperatorController a, OperatorController b) { return new OperatorController(a.num * b.den + b.num * a.den, a.den * b.den); } // overload operator * public static OperatorController operator *(OperatorController a, OperatorController b) { return new OperatorController(a.num * b.num, a.den * b.den); } }
上面的OperatorController类提供了一个构造函数和"+","*"的重载方法。
下面是一组执行代码:
var a = new OperatorController(1, 2); var b = new OperatorController(3, 7); var c = new OperatorController(2, 3); var d = a + b; var e = a * b + c;
为了便于理解,我将执行过程中的变量一一输出:
a
Response.Write("a:" + a.num + "--" + a.den + "<br/>");
输出:a:1--2
b
Response.Write("b:" + b.num + "--" + b.den + "<br/>");
输出:b:3--7
c
Response.Write("c:" + c.num + "--" + c.den + "<br/>");
输出:b:2--3
d
Response.Write("d:" + d.num + "--" + d.den + "<br/>");
输出:d:13--14
e
Response.Write("e:" + e.num + "--" + e.den + "<br/>");
输出:e:37--42
接下来,重点说一下重载"+"是如何实现的:
以var d = a + b;为例, 分解一下执行过程,
step1. 执行"+"重载方法
public static OperatorController operator +(OperatorController a, OperatorController b) { return new OperatorController(a.num * b.den + b.num * a.den, a.den * b.den); }
当a和b做"+"运算时,会把a和b作为参数传入到这个重载方法(重载运算符只支持两个参数),通过运算可以演变成
public static OperatorController operator +(OperatorController a, OperatorController b) { return new OperatorController(13, 14); }
step2. 执行构造函数
public OperatorController(int num, int den) { this.num = num; this.den = den; }
所以执行Response.Write("d:" + d.num + "--" + d.den + "<br/>");时,会输出d:13--14
在下面重载"=="的方法里,没有自己的业务逻辑,跟Equals(x,y)效果一样
public static bool operator ==(BaseEntity x, BaseEntity y) { return Equals(x, y); }