一.創建一個窗體
二.創建一個類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(); }