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. C++运算符重载

    2024-07-10 14:10:05       30 阅读
  2. C++:运算符重载

    2024-07-10 14:10:05       43 阅读
  3. C++ 运算符重载

    2024-07-10 14:10:05       25 阅读
  4. C++基础——运算符重载

    2024-07-10 14:10:05       24 阅读
  5. C++运算符重载

    2024-07-10 14:10:05       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 14:10:05       4 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 14:10:05       5 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 14:10:05       4 阅读
  4. Python语言-面向对象

    2024-07-10 14:10:05       5 阅读

热门阅读

  1. 物联网应用,了解一点 WWAN全球网络标准

    2024-07-10 14:10:05       11 阅读
  2. Jupyter Notebook详尽安装教程

    2024-07-10 14:10:05       7 阅读
  3. 实现淘客返利系统中的用户登录与权限管理

    2024-07-10 14:10:05       6 阅读
  4. 【力扣】每日一题—第70题,爬楼梯

    2024-07-10 14:10:05       8 阅读
  5. mysql快速精通(一)DQL数据查询语言

    2024-07-10 14:10:05       10 阅读
  6. 408第二轮复习 数据结构 第七章查找

    2024-07-10 14:10:05       11 阅读
  7. Python中的迭代器与可迭代对象的概念及其关系

    2024-07-10 14:10:05       10 阅读
  8. 大数据面试题之Greenplum(2)

    2024-07-10 14:10:05       7 阅读
  9. 准备GPU H20机器k8s环境时用到的链接

    2024-07-10 14:10:05       8 阅读