一.创建一个窗体
二.创建一个类Operator里面有两个操作数和一个方法
public abstract class Operator { public abstract int Calc(); //计算数 public int NumLeft { get; set; } public int NumRight { get; set; } }
三.创建一个Add类
public class Add:Operator { public override int Calc() { return this.NumLeft + this.NumRight; } }
四.创建一个Sub类
public class Sub:Operator { public override int Calc() { return this.NumLeft - this.NumRight; } }
五.创建一个Mul类
public class Mul:Operator { public override int Calc() { return this.NumLeft * this.NumRight; } }
六.创建一个div类
public class Div:Operator { public override int Calc() { int result = 0; if (NumLeft == 0) { throw new Exception("除数不能为0"); } else { result=this.NumLeft / this.NumRight; } return result; } }
七. 创建一个类似于工厂的类
public class Factory { //静态的 返回值类型 参数 public static Operator cu(string Type) { Operator oper=null; switch (Type) { case"+": oper=new Add(); break; case"-": oper=new Sub(); break; case"*": oper=new Mul(); break; case"/": oper=new Div(); break; } return oper; } }
八.在主窗体的结果按钮中添加
private void btOk_Click(object sender, EventArgs e) { int num1=Convert.ToInt32( txtLfet.Text); string oper = cb.Text; int num2 = Convert.ToInt32(txtRight.Text); //04.调用工厂的静态方法,传入类型 ,获取返回值 Operator part = Factory.cu(oper); part.NumLeft = num1; part.NumRight = num2; int result = 0; //05.调用对应父类变量的Calc()完成计算,接收返回值 try { result = part.Calc(); } catch (Exception ex) { MessageBox.Show(ex.Message); } //06.在Label中显示 label1.Text = result.ToString(); }
时间: 2024-10-16 03:44:37