using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace lianxi { public class OPeration { private double _numberA = 0; private double _numberB = 0; public double NumberA { get { return _numberA; } set { _numberA = value; } } public double NumberB { get { return _numberB; } set { _numberB = value; } } public virtual double GetResult() { double result = 0; return result; } } }
在父类中定义 virtual 方法,如果在子类中进行了 override(重写),可以进行多态调用。 如果在子类中未进行 override,程序并不会报错。
class OperationAdd:OPeration //继承运算类 { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } }
class OperationSub :OPeration//继承运算类 { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } }
class OperationMul:OPeration { public override double GetResult() { double result = 0; result = NumberA * NumberB; return result; } }
class OperationDiv:OPeration { public override double GetResult() { double result = 0; if (NumberB == 0) throw new Exception("除数不可以为零"); result = NumberA / NumberB; return result; } }
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; } }
Console.WriteLine("请输入第一个数字A:"); double numberA = double.Parse(Console.ReadLine()); Console.WriteLine("请输入运算符:+ - * /:"); string symbol = Console.ReadLine(); Console.WriteLine("请输入第二个数字B:"); double numberB = double.Parse(Console.ReadLine()); OPeration oper = OperationFactory.createOperate(symbol); oper.NumberA = numberA; oper.NumberB = numberB; double result = oper.GetResult(); Console.WriteLine("结果是:"+ result); Console.ReadLine();