40.C# 运算符重载

2024-03-11  本文已影响0人  技术老小子

摘要


C#是一种面向对象的编程语言,其中包含了用户自定义类型的支持。在C#中,可以使用用户自定义类型的运算符,也就是重载运算符。

重载运算符是具有特殊名称的函数,是通过关键字 operator 后跟运算符的符号来定义的。这些重载运算符可以用来对用户自定义类型的对象进行算术、比较、逻辑和位运算等操作。

通过重载运算符,您可以使用用户自定义类型的对象进行各种操作,这对于构建复杂的程序和应用程序非常有用。重载运算符可以大大提高代码的可读性和可维护性,使程序更加灵活和可扩展。

正文


运算符 描述
+, -, !, ~, ++, -- 这些一元运算符只有一个操作数,且可以被重载。
+, -, *, /, % 这些二元运算符带有两个操作数,且可以被重载。
==, !=, <, >, <=, >= 这些比较运算符可以被重载。
&&,
+=, -=, *=, /=, %= 这些赋值运算符不能被重载。
=, ., ?:, ->, new, is, sizeof, typeof 这些运算符不能被重载。

创建一个Box类

internal class Box
{
    public int Length { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }

    public int Volume()
    {
        return Length * Width * Height;
    }

    //两个箱子相加
    public static Box operator +(Box a, Box b)
    {
        Box box = new Box();
        box.Length = a.Length + b.Length;
        box.Width = a.Width + b.Width;
        box.Height = a.Height + b.Height;
        return box;
    }

    //两个箱子是否相同
    public static bool operator ==(Box a, Box b)
    {
        if(a.Length==b.Length && a.Width==b.Width && a.Height == b.Height)
        {
            return true;
        }
        return false;
    }

    //两个箱子是否不相同
    public static bool operator !=(Box a, Box b)
    {
        if (a.Length == b.Length && a.Width == b.Width && a.Height == b.Height)
        {
            return false;
        }
        return true;
    }

    public void PrintSize()
    {
        Console.WriteLine(this.Length * this.Width * this.Height);
    }
}

static void Main(string[] args)
{
    Box box1 = new Box();
    Box box2 = new Box();

    box1.Length = 100;
    box1.Width = 50;
    box1.Height = 50;

    box2.Length = 30;
    box2.Width = 10;
    box2.Height = 10;

    Box box3 = box1 + box2;
    box3.PrintSize();

    bool isSame=box1==box2;
    Console.WriteLine(isSame);
}

上一篇 下一篇

猜你喜欢

热点阅读