封裝計算方法實現面向對象計算器。
阿新 • • 發佈:2019-03-01
override main lse program set todo 一個 ring alc
public abstract class Calculator { public double Number1 { get; set; } public double Number2 { get; set; } public abstract double Calculate(); }
class Add : Calculator { public Add(double n1,double n2) { this.Number1 = n1;this.Number2 = n2; } public override double Calculate() { return Number1 + Number2; } }
class Sub : Calculator { public Sub(double n1,double n2 ) { this.Number1 = n1; this.Number2 = n2; }public override double Calculate() { return Number1 - Number2; } }
class Program { static void Main(string[] args) { Console.WriteLine("第一個數"); double Number1 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("操作符"); string Operate= Console.ReadLine(); Console.WriteLine("第二個數"); double Number2= Convert.ToDouble(Console.ReadLine()); Calculator calculator = null; switch (Operate) { case "+": calculator = new Add(Number1, Number2); break; case "-": calculator = new Sub(Number1, Number2); break; } if (calculator!=null) { Console.WriteLine("結果是:{0}",calculator.Calculate()); } else { Console.WriteLine("沒有這種操作"); } } }
優化:
Calculator calculator = GetComputeObject(Operate, Number1, Number2);
private static Calculator GetComputeObject(string perate, double number1, double number2) { Calculator result = null; switch (perate) { case "+": result = new Add(number1, number2); break; case "-": result = new Sub(number1, number2); break; } return result; }
封裝計算方法實現面向對象計算器。