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、运行结果
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大浪淘沙胡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值