C# Delegate 委派

計算機

Delegate 委派 是一個類,它定義方法的類形,使的方法可以當作另一個方法的參數來進行傳遞。

  1. 宣告委派行別
  2. 建立委派可以呼叫的方法
        delegate int MyDelegate(int opd1,int opd2);
        class MyMath
        {
            public static int Add(int opd1, int opd2)
            {
                return opd1 + opd2;
            }
            public static int Subtract(int opd1, int opd2)
            {
                return opd1 - opd2;
            }
            public static int Multiply(int opd1, int opd2)
            {
                return opd1 * opd2;
            }
            public static int Divide(int opd1, int opd2)
            {
                return opd1 / opd2;
            }
        }
        

建立計算按鈕

        private void Caulate_Click(object sender, EventArgs e)
        {
            int opd1, opd2;
            opd1 = Convert.ToInt32(Input_1.Text);
            opd2 = Convert.ToInt32(Input_2.Text);
            if (Add.Checked)
            {
                MyDelegate Handle = new MyDelegate(MyMath.Add);
                Output.Text = "加法=" + Handle(opd1,opd2);
            }
            if (Subtract.Checked)
            {
                MyDelegate Handle = new MyDelegate(MyMath.Subtract);
                Output.Text = "減法=" + Handle(opd1, opd2);
            }
            if (Multiply.Checked)
            {
                MyDelegate Handle = new MyDelegate(MyMath.Multiply);
                Output.Text = "乘法=" + Handle(opd1, opd2);
            }
            if (Divide.Checked)
            {
                MyDelegate Handle = new MyDelegate(MyMath.Divide);
                Output.Text = "除法=" + Handle(opd1, opd2);
            }
        }
        

運行結果

加法

加法

減法

減法

乘法

乘法

除法

除法

原始碼下載

https://mega.nz/#!fbJzDKQA!qM7eZraykUYQKBI-aWlmSP-NAMsROt-DNr9JWeKrpe0

Last modification:November 14th, 2018 at 10:46 pm