close

image

   1: class Operation
   2: {
   3:     public virtual double operation(int x, int y)
   4:     {
   5:         return x * y;
   6:     }
   7: }
   8: class Addition : Operation
   9: {
  10:     public override double operation(int x, int y)
  11:     {
  12:         return (x + y);
  13:     }
  14: }
  15:  
  16: private void button1_Click(object sender, EventArgs e)
  17: {
  18:     if (comboBox1.SelectedIndex == 0)
  19:     {
  20:         Operation multiplication = new Operation();
  21:         txtResult.Text = multiplication.operation( Convert.ToInt32(txtNum1.Text.Trim()), Convert.ToInt32(txtNum2.Text.Trim() )).ToString();
  22:     }
  23:     else
  24:     {
  25:         Operation addition = new Addition();
  26:         txtResult.Text = addition.operation(Convert.ToInt32(txtNum1.Text.Trim()), Convert.ToInt32(txtNum2.Text.Trim())).ToString();
  27:     }

28: }


=======================================================================

Multiplication繼承Operation, 同樣的Addition也是繼承Operation, 不過Addition有重寫operation方法

   1: class Operation
   2:    {
   3:        public virtual double operation(int x, int y)  // virtual method可以再重新定義
   4:        {
   5:            return x * y;
   6:        }
   7:    }
   8:    class Multiplication : Operation
   9:    {
  10:  
  11:    }
  12:    class Addition : Operation
  13:    {
  14:        public override double operation(int x, int y)
  15:        {
  16:            return (x + y);
  17:        }
  18:    }

以下為Operation陣列, 一個存放乘法, 一個存放加法物件

   1: private void button2_Click(object sender, EventArgs e)
   2: {
   3:     Operation[] op = new Operation[2];         // Operation陣列
   4:     op[0] = new Multiplication();              // 存放乘法
   5:     op[1] = new Addition();                    // 存放加法
   6:     MessageBox.Show( "Multiplication: " + op[0].operation( int.Parse(txtNum1.Text), int.Parse(txtNum2.Text)).ToString() );
   7:     MessageBox.Show("Addition: " + op[1].operation(int.Parse(txtNum1.Text), int.Parse(txtNum2.Text)).ToString());
   8: }

結合下拉選單

   1: Operation[] op = new Operation[2];         // Operation陣列
   2:   op[0] = new Multiplication();              // 存放乘法
   3:   op[1] = new Addition();                    // 存放加法
   4:   int i = comboBox1.SelectedIndex;
   5:   txtResult.Text = op[i].operation(int.Parse(txtNum1.Text), int.Parse(txtNum2.Text)).ToString();
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 me1237guy 的頭像
    me1237guy

    天天向上

    me1237guy 發表在 痞客邦 留言(0) 人氣()