程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 多態計算機程序,多態計算機

多態計算機程序,多態計算機

編輯:C#入門知識

多態計算機程序,多態計算機


一.創建一個窗體

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

  

 

  

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved