C# 重载

重载主要包括方法重载和运算符重载。

方法重载:

class Area
        {
            //计算矩形面积
            public int Count(int x, int y)
            {
                return x * y;
            }
            //计算圆面积
            public double Count(double r)
            {
                return Math.PI * r * r;
            }
            //计算椭圆面积
            public double Count(double a, double b)
            {
                return Math.PI * a * b;
            }
        }
        static void Main(string[] args)
        {
            Area area = new Area();
            Console.WriteLine("计算矩形面积为:" + area.Count(4, 6));
            Console.WriteLine("计算圆面积为:" + area.Count(3.4));
            Console.WriteLine("计算椭圆面积为:" + area.Count(2.5, 3.6));
            Console.ReadKey();
        }

运行结果:

计算矩形面积为:24

计算圆面积为:36.316811075498

计算椭圆面积为:28.2743338823001

运算符重载:

class Test
        {
            public int real;
            public int img;
            public Test(int real, int img) //类的构造函数
            {
                this.real = real; //给类的成员赋值
                this.img = img;
            }
            //运算符重载关键字为operator
            public static Test operator +(Test x, Test y)  //这里必须声明为public 和 static
            {
                return new Test(x.real + y.real, x.img + y.img);
            }
        }
        static void Main(string[] args)
        {
            Test t1 = new Test(2, 3); //实例对象
            Test t2 = new Test(4, 5);
            Test t3 = t1 + t2;  //这里无法直接对实例对象相加,所以必须要用到“重载”
            Console.WriteLine("t3.real={0}, t3.img={1}", t3.real, t3.img);
            Console.ReadKey();
        }

运行结果

t3.real=6, t3.img=8

在运算符重载的使用过程中,应注意以下情况。

1、并非所有运算符都能被重载,不能被重载的运算符包括“=”、“?:”、“->”、“new”、“is”、“sizeof”和“typeof”。

2、重载运算符不能改变原来运算符的优先级和操作数。

3、比较运算符必须成对重载,如“==”和“!=”,“>”和“<”等。

4、重载运算符可由派生类继承。

原文地址:https://www.cnblogs.com/han1982/p/2698022.html