标签:
运算类
public class Operation { private double _numberA = 0; private double _numberB = 0; public double NumberA { get; set; } public double NumberB { get; set; } public virtual double GetResult() { double result = 0; return result; } }
加减乘除类
//加发类 public class OperationAdd : Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } //减法类 public class OperationSub : Operation { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } //乘法类 public class OperationMul : Operation { public override double GetResult() { double result = 0; result = NumberA *NumberB; return result; } } //除法类 public class OperationDiv: Operation { public override double GetResult() { double result = 0; result = NumberA / NumberB; return result; } }
简单运算工厂
public class OperationFactory { public static Operation createOperate(string operate) { Operation oper = null; switch (operate) { case "+": oper=new OperationAdd(); break; case "-": oper=new OperationSub(); break; case "*": oper=new OperationMul(); break; case "/": oper=new OperationDiv(); break; } return oper; } }
调用代码
static void Main(string[] args) { try { Console.Write("请输入数字A:"); string strNumberA = Console.ReadLine(); Console.Write("请选择运算符号(+,-,*,/):"); string strOperate = Console.ReadLine(); Console.Write("请选择数字B:"); string strNumberB = Console.ReadLine(); Operation oper; oper = OperationFactory.createOperate(strOperate); oper.NumberA = Convert.ToDouble(strNumberA); oper.NumberB = Convert.ToDouble(strNumberB); double result = oper.GetResult(); Console.WriteLine("结果是:" + result); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine("您输入的有错:"+ex.Message); } }
标签:
原文地址:http://www.cnblogs.com/gouguo/p/4316841.html