c#中的运算符重载例子

114 阅读1分钟

下面的例子重载了+号,实现了两个矩形类相加

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class RectPrimary
    {
        private double dWidth = 0d;
        private double dHeight = 0d;
        public void setWidth(double dlen)
        {
            dWidth = dlen;
        }
        public void setHeight(double dlen)
        {
            dHeight = dlen;
        }
        public double getWidth()
        {
            return dWidth;
        }
        public double getHeight()
        {
            return dHeight;
        }
        public static RectPrimary operator+ (RectPrimary rc1,RectPrimary rc2)
        {
            RectPrimary tempRect = new RectPrimary();
            tempRect.setWidth(rc1.getWidth()+rc2.getWidth());
            tempRect.setHeight(rc1.getHeight()+rc2.getHeight());
            return tempRect;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            RectPrimary rc1 = new RectPrimary();
            RectPrimary rc2 = new RectPrimary();
            rc1.setHeight(1d);
            rc2.setHeight(1d);
            rc1.setWidth(1d);
            rc2.setWidth(1d);
            RectPrimary rc3 = new RectPrimary();
            rc3 = rc1 + rc2;
            double dw = rc3.getWidth();
            double dh = rc3.getHeight();
            Console.WriteLine("rc3 的宽为:{0},rc3 的高为:{1}",dw,dh);
            Console.ReadKey();
        }
    }
}