关键字
operator
特点
1. 一定是一个public的静态方法
2. 逻辑处理自定义
作用
让自定义的类或结构体能够使用运算符
基本语法:public static 返回类型 operator 运算符(参数列表)
{
//do something
}
实例:
class Point
{
public int x;
public int y;
public Point (int x, int y) { this.x = x; this.y = y; }
public static Point operator + (Point p1, Point p2)
{
Point res = new Point (0, 0);
res.x = p1.x + p2.x;
res.y = p1.y + p2.y;
return res;
}
public static Point operator + (Point p1, int value)
{
Point res = new Point (0, 0);
res.x = p1.x + value;
res.y = p1.y;
return res;
}
public override string ToString ()
{
return string.Format ("({0},{1})", this.x, this.y);
}
}
class Program
{
static void Main (string[] args)
{
Point p1 = new Point (3, 4);
Point p2 = new Point (2, 2);
Console.WriteLine (p1 + p2); //(5,6)
Console.WriteLine (p1 + 1); //(4,4)
}
}
注意
1. 条件运算符需要成对实现
2. 参数列表中至少要有一个为自定义的类或结构体
3. 一个符号可以多个重载
4. 不能使用ref和out