20250529-C#知识:运算符重载
C#知识:运算符重载
运算符重载能够让我们像值类型数据那样使用运算符对类或结构体进行运算,并且能够自定义运算逻辑。
1、运算符重载及完整代码示例
- 作用是让自定义的类或者结构体能够使用运算符
- 运算符重载一定是public static的
- 可以把运算符看成一个函数
- 例如双目运算符’+'就是一个具有两个参数的函数
- 运算符重载是根据运算符的参数的不同进行重载,类比函数重载
- 条件运算符要成对重载
- 不能使用ref和out关键字
- 重载不改变运算符优先级
namespace LearnOperatorOverloading
{internal class Program{class Rect{public float height;public float width;public Rect() : this(2, 2) { }public Rect(float height, float width){this.height = height;this.width = width;}public float GetArea() => height * width;//条件运算符要成对重载public static bool operator <(Rect a, Rect b){if(a.height * a.width < b.height * b.width)return true;return false;} public static bool operator >(Rect a, Rect b){if(a.height * a.width > b.height * b.width)return true;return false;}public static Rect operator + (Rect a, Rect b) => new Rect(a.height + b.height, a.width + b.width);public static Rect operator *(Rect a, Rect b) => new Rect(a.height * b.height, a.width * b.width);}static void Main(string[] args){Rect rect = new Rect();Console.WriteLine(rect.GetArea()); //4 Rect rect2 = new Rect(3, 5);Console.WriteLine(rect2.GetArea()); //15Console.WriteLine((rect2 + rect).GetArea()); //35Console.WriteLine((rect * rect2).GetArea()); //60//先乘后加,运算符重载后运算顺序不变Console.WriteLine((rect + rect * rect2).GetArea()); //96if (rect < rect2) //Rect < Rect2Console.WriteLine("Rect < Rect2");elseConsole.WriteLine("Rect >= Rect2");}}
}
2、不可重载的运算符
- 赋值运算符=
- 点. 索引[] 强转()
- 三目运算符 ?:
- 逻辑或|| 和逻辑与&&
3、参考资料
- 《唐老狮C#》
本篇结束,感谢您的阅读~