欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > C#运算符重载

C#运算符重载

2025/3/29 5:49:11 来源:https://blog.csdn.net/qq_27474555/article/details/140214608  浏览:    关键词:C#运算符重载

1、运算符重载
运算符重载是指重定义C#内置的运算符。
程序员也可以使用用户自定义类型的运算符。重载运算符是具有特殊名称的函数,是通过关键字 operator 后跟运算符的符号来定义的。与其他函数一样,重载运算符有返回类型和参数列表。
2、在Box类中定义运算符重载

public class Box{private double length;[Description("长度")]public double Length{get { return length; }set { length = value; }}private double width;[Description("宽度")]public double Width{get { return width; }set { width = value; }}private double height;[Description("高度")]public double Height{get { return height; }set { height = value; }}public double GetVolume(){return length * width * height;}public static bool operator == (Box box1, Box box2){return (box1.length == box2.length) && (box1.width == box2.width) && (box1.height == box2.height);}public static bool operator != (Box box1, Box box2){return (box1.length != box2.length) || (box1.width != box2.width) || (box1.height != box2.height);}}

3、应用Box类

Box box1 = new Box();Box box2 = new Box();Box box3 = new Box();double volume = 0.0;box1.Length = 3.0;box1.Width = 4.0;box1.Height = 5.0;volume=box1.GetVolume();Console.WriteLine($"Box1的体积是{volume}");box2.Length = 6.0;box2.Width = 7.0;box2.Height = 8.0;volume = box2.GetVolume();Console.WriteLine($"Box2的体积是{volume}");bool flag=box1 == box2;Console.WriteLine($"Box1==Box2:{flag}");flag = box1 != box2;Console.WriteLine($"Box1!=Box2:{flag}");

4、运行结果
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词