C#中的运算符重载

在C#中多态性的概念非常简单。
运算符重载是一种多态性的形式。
运算符重载意味着在应用于用户定义的数据类型时提供正常运算符的能力。
所有C#二进制运算符和联合运算符都可以重载,例如+, - ,*,/,!,++。
运算符重载是使用称为运算符函数的特殊功能,以便在C#中重载。
该函数必须是公共的或者静态的。

C# 运算符重载语法

return-data-type operator symbol-of-operator (parameters)

{

//函数的主体

}

C#中的运算符重载示例

using System;

using System.Collections.Generic;

using System.Text;

namespace OperatorOvrloadingApplication

{

    class Box

    {

        private double length;      //Length of a box

        private double breadth;     //Breadth of a box

        private double height;      //Height of a box

        public double showVolume()

        {

            return length * breadth * height;

        }

        public void setLength(double len)

        {

            length = len;

        } 

        public void setBreadth(double bre)

        {

            breadth = bre;

        }

        public void setHeight(double hei)

        {

            height = hei;

        }

        //重载 + 运算符用来将两个对象相加

        public static Box operator +(Box b, Box c)

        {

            Box box = new Box();

            box.length = b.length + c.length;

            box.breadth = b.breadth + c.breadth;

            box.height = b.height + c.height;

            return box;

        }

    }

    class calculate

    {

        static void Main(string[] args)

        {

            Box Box1 = new Box();         //定义Box类型的变量Box1

            Box Box2 = new Box();         //定义Box类型的变量Box2

            Box Box3 = new Box();         //定义Box类型的变量Box3

            double volume = 0.0;    //临时变量,用于保存体积

            //设置Box1的属性

            Box1.setLength(1.0);

            Box1.setBreadth(2.0);

            Box1.setHeight(3.0);

            //设置Box2的属性

            Box2.setLength(4.0);

            Box2.setBreadth(5.0);

            Box2.setHeight(6.0);

            //计算Box1体积

            volume = Box1.showVolume();

            Console.WriteLine("Volume of Box1 : {0}", volume);

            //计算Box2体积

            volume = Box2.showVolume();

            Console.WriteLine("Volume of Box2 : {0}", volume);

            //将两个对象相加

            Box3 = Box1 + Box2;

           //查看Box3体积

            volume = Box3.showVolume();

            Console.WriteLine("Volume of Box3 : {0}", volume);

            Console.ReadKey();

        }

    }

}
日期:2020-04-11 23:03:46 来源:oir作者:oir