面向对象的三大特性:封装,继承,多态。
本文只是第一章计算器例子的源代码分享:
1,定义一个运算基类,所有的运算都继承自它:
/// <summary> /// 所有运算的基类 /// </summary> class Operation { public double NumberA; public double NumberB; /// <summary> /// 计算结果让子类重写 /// </summary> public virtual double GetResult() { double result=0d; return result; } }
2,定义所有的运算类,继承自运算基类Operation:
View Code
/// <summary> /// 下面的类都继承自Operation,重载了GetResult() /// </summary> class OperationAdd : Operation { public override double GetResult() { return (NumberA + NumberB); } } class OperationSub : Operation { public override double GetResult() { return (NumberA - NumberB); } } class OperationMul : Operation { public override double GetResult() { return (NumberA * NumberB); } } class OperationDiv : Operation { public override double GetResult() { if (NumberB == 0) throw new Exception("除数不能为0"); return (NumberA / NumberB); } }
3,定义一个简单工厂类,决定实例化哪一个对象:
View Code
/// <summary> /// 简单工厂类,判断创建哪一个实例 /// </summary> class OperationFactory { /// <summary> /// 根据运算符判断实例化哪个对象,静态方法可以直接调用 /// </summary> /// <param name="opr">运算符</param> /// <returns>被实例化的运算对象</returns> public static Operation CreateObject(string opr) { Operation OpeObject = null; switch (opr) { case "+": OpeObject = new OperationAdd(); break; case "-": OpeObject = new OperationSub(); break; case "*": OpeObject = new OperationMul(); break; case "/": OpeObject = new OperationDiv(); break; } return OpeObject; } }
4,在Main方法中测试:
View Code
class Program { static void Main(string[] args) { while (true) { try { Console.WriteLine("请输入两个数(每行一个):"); string NumberA = Console.ReadLine(); string NumberB = Console.ReadLine(); Console.WriteLine("请输入运算符+,-,*,/"); string Opr = Console.ReadLine(); Operation ope = OperationFactory.CreateObject(Opr); ope.NumberA = Convert.ToDouble(NumberA); ope.NumberB = Convert.ToDouble(NumberB); string rusult = Convert.ToString(ope.GetResult()); Console.WriteLine("运算结果是:{0}", rusult); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }