多態電腦程式

來源:互聯網
上載者:User

標籤:

一.建立一個表單

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

  

 

  

 

多態電腦程式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.