多态
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; } }
时间: 2024-10-13 16:05:07