Compartir tecnología

Sobrecarga del operador C#

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

1、Sobrecarga del operador
La sobrecarga de operadores se refiere a la redefinición de los operadores integrados de C#.
programador También se pueden utilizar tipos de operadores definidos por el usuario. Un operador sobrecargado es una función con un nombre especial, definido por la palabra clave operador seguida del símbolo del operador. Al igual que otras funciones, los operadores sobrecargados tienen un tipo de retorno y una lista de parámetros.
2. Defina la sobrecarga de operadores en la clase 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);
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

3. Aplicar clase de caja

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}");
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

4. Resultados de la operación
Insertar descripción de la imagen aquí