一、C#当中可以进行重载和不可重载的运算符:
1.简单的说明:
1.从上图中可以看到,可以重载的和不可以进行重载的运算符,比较特殊的是第二行和倒数第三行,的运算符,为什么会说它们特殊,是因为(第三行)在这一行当中,不能重载当中的一个运算符,必须成对的重载,什么意思呢,比如:== 和!= 这两个运算符,你必须要都进行重载才可以,不然编译器会提示让你添加(会报错的)剩下的那几个运算符>< <=>=之类的也是一样的,必须要成对的重载;
2.第三行说完了来说说倒数第二行,他特殊的地方是比如:你重载了+运算符,那么对就的+=运算符也会自动的添加实现,不用你显示的去重载,.NET已经自动的生成了,当然-也是一样的;
3.不能重载的运算符上图也标记了;
2.代码例子:
想了半天最后还是觉的书上的例子《C#高级编程第五版》的例子比较好:
public class Point:IComparable{ public int X{get;set;} public int Y{get;set;} public Point(int xPos,int yPos){X = xPost; Y=yPos;} public Point(){} //重写Equals方法与GetHashCode方法 public override bool Equals(object obj){return obj.ToString() == this.ToString();} public override int GetHashCode(){return this.ToString().GetHashCode();} //实现Icomparable比较方法 public int CompareTo(object obj){ if (obj is Point){ Point p = (Point)obj; if (this.X > p.X && this.Y > p.Y) return 1; if (this.X < p.X && this.Y < p.Y) return -1; else return 0; }else throw new ArgumentException(); }
//+-运算符重载 public static Point operator +(Point p1,Point p2){return new Point(p1.X+p2.X,p1.Y+p2.Y);} public static Point operator -(Point p1,Point p2){return new Point(p1.X-p2.X,p1.Y-p2.Y);} //== !=运算符重载***必须要成对的重载这两个运算符 public static Point operator ==(Point p1,Point p2){return p1.Equals(p2);} public static Point operator !=(Point p1,Point p2){return !p1.Equals(p2);} //一元运算符的重载:++,-- public static Point operator ++(Point p1){return new Point(p1.X++,p1.Y++);} public static Point operator --(Point p1){return new Point(p1.X--,p1.Y--);} //对>< ,<=,>=运算符进行重载 public static bool operator >(Point p1,Point p2){ return (p1.CompareTo(p2)<0);} public static bool operator <(Point p1, Point p2){return (p1.CompareTo(p2)>0);} public static bool operator >=(Point p1,Point p2){return (p1.CompareTo(p2)<=0);} public static bool operator <=(Point p1,Point p2){return(p1.CompareTo(p2)>=0);}
public override string ToString(){return string.Format("X:{0} Y:{0}",X,Y);} }
下面就是测试的例子:
static void Main(string[] args)
{
Point p1 = new Point(10,20);
Point p2 = new Point(30,40);
Console.WrilteLine((p1+p2).ToString()); //X:40 Y:60
}