运算符重载可以对类使用。关键字operator .
可以重载的运算符:一元运算符:+,-,!,~,++,--,true,false
二元运算符:+,-,*,/,%,&,|,`,<<,>>
比较运算符:==,!=,<,>,<=,>=
示例代码如下:
//运算符重载
- public class AddClass1 {
- public int val;
- //使用关键字operator 运算符号,+运算符
- public static AddClass1 operator +(AddClass1 op1,AddClass1 op2) {
- AddClass1 returnVal = new AddClass1();
- returnVal.val = op1.val + op2.val;
- return returnVal;
- }
- //-运算符
- public static AddClass1 operator -(AddClass1 op1) {
- AddClass1 returnVal = new AddClass1();
- returnVal.val = -op1.val;
- return returnVal;
- }
- //+运算符
- public static AddClass3 operator +(AddClass1 op1,AddClass2 op2) {
- AddClass3 returnVal = new AddClass3();
- returnVal.val = op1.val + op2.val;
- return returnVal;
- }
- //> < >= <=必须成对出现
- public static bool operator >=(AddClass1 op1, AddClass1 op2) => op1.val >= op2.val;
- public static bool operator <=(AddClass1 op1, AddClass1 op2) => !(op1.val >= op2.val);
- // == !=运算符需要重写Equals() 和 GetHashCode()方法
- public static bool operator ==(AddClass1 op1, AddClass1 op2) => (op1 == op2);
- public static bool operator !=(AddClass1 op1, AddClass1 op2) => !(op1==op2);
- public override bool Equals(object obj) {
- if (obj is AddClass1) //is运算符的使用
- {
- return val == ((AddClass1)obj).val;
- }
- else {
- throw new ArgumentException("can't compare"+obj.GetType().ToString());
- }
- }
- public override int GetHashCode() => val;
- }
- public class AddClass2 {
- public int val;
- }
- public class AddClass3 {
- public int val;
- }
- public class Program{
- public static void Main(string[] args){
- AddClass1 op1 = new AddClass1//对象初始化器的使用
- {
- val = 5
- };
- Console.WriteLine(op1.val);
- AddClass1 op2 = new AddClass1();
- op2.val = 4;
- Console.WriteLine(op2.val);
- AddClass1 op3 = op1 + op2;//+运算符
- Console.WriteLine(op3.val);
- AddClass1 op4 = -op3;//-运算符
- Console.WriteLine(op4.val);
- bool t = op1 >= op2;//>=运算符
- bool t1 = op1 <= op2;//<=运算符
- Console.WriteLine(t + "//" + t1);
- if (op1.GetType() == typeof(AddClass1))
- {
- Console.WriteLine(op1.GetType().ToString());
- }
- }
- }