码迷,mamicode.com
首页 > Windows程序 > 详细

.Net学习笔记----2015-07-21(C#基础复习06,多态复习)

时间:2015-07-21 14:32:46      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

多态

1、虚方法  virtual

2、抽象类  abstract

 

面向对象计算器 案例:

技术分享

    class Program
    {
        static void Main(string[] args)
        {
            //实现多态:虚方法、抽象类、接口
            //简单工厂实现简单计算器效果
            while (true)
            {
                Console.WriteLine("请输入第一个数字");
                double n1 = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine("请输入第二个数字");
                double n2 = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine("请输入运算符");
                string opera = Console.ReadLine();
                OperaFather opf = GetOpera(opera, n1, n2);
                double res = opf.GetResult();
                Console.WriteLine(res);
            }
            Console.ReadKey();
        }

        public static OperaFather GetOpera(string opear,double n1, double n2)
        {
            OperaFather opf = null;
            switch(opear)
            {
                case "+": opf = new Add(n1,n2);
                    break;
                case "-": opf = new Sub(n1, n2);
                    break;
                case "*": opf = new Cheng(n1, n2);
                    break;
                case "/": opf = new Chu(n1, n2);
                    break;
            }
            return opf;
        }
    }
    public abstract class OperaFather
    {
        public OperaFather(double n1, double n2)
        {
            this.NumberOne = n1;
            this.NumberTwo = n2;
        }
        public double NumberOne
        { get; set; }
        public double NumberTwo
        { get; set; }

        public abstract double GetResult();
    }
    class Add : OperaFather
    {
        public Add(double n1, double n2)
            : base(n1, n2)
        {

        }
        public override double GetResult()
        {
            return this.NumberOne + this.NumberTwo;
        }
    }
    class Sub : OperaFather
    {
        public Sub(double n1, double n2)
            : base(n1, n2)
        {

        }
        public override double GetResult()
        {
            return this.NumberOne - this.NumberTwo;
        }
    }
    class Cheng : OperaFather
    {
        public Cheng(double n1, double n2)
            : base(n1, n2)
        {

        }
        public override double GetResult()
        {
            return this.NumberOne * this.NumberTwo;
        }
    }
    class Chu : OperaFather
    {
        public Chu(double n1, double n2)
            : base(n1, n2)
        {

        }
        public override double GetResult()
        {
            return this.NumberOne / this.NumberTwo;
        }
    }

 

.Net学习笔记----2015-07-21(C#基础复习06,多态复习)

标签:

原文地址:http://www.cnblogs.com/mikie/p/4664186.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!