學習C#中的委託

來源:互聯網
上載者:User

先是自己寫的一個小例子

 

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp
{
    class DelegateDemo  
    {
        delegate double processDelagate(double pra1,double pra2);        

        static double Multiply(double pra1,double pra2)
        {
            return pra1 * pra2;
        }
        static double Divide(double pra1, double pra2)
        {
            return pra1 / pra2;
        }

        delegate string stringDelegate(string str);
        static string Println(string str)
        {
            return str;
        }

        public static void Main(string[] args)
        {
            //processDelagate委託的測試例子
            processDelagate process;
            Console.WriteLine("請輸入數字A!");
            string input1 = Console.ReadLine();
            Console.WriteLine("請輸入數字B!");
            string input2 = Console.ReadLine();
            Console.WriteLine("請輸入操作符號(M代表乘法,D代表除法)!");
            string ope = Console.ReadLine();
            if (ope == "M")
                process = new processDelagate(Multiply);
            else if (ope == "D")
                process = new processDelagate(Divide);
            else
                process = new processDelagate(Divide);                
            Console.WriteLine("Result:{0}", process(Convert.ToDouble(input1), Convert.ToDouble(input2)));

            //stringDelegate委託的測試例子
            stringDelegate printStr;
            Console.WriteLine("請輸入你的文字:");
            string str = Console.ReadLine();
            printStr = new stringDelegate(Println);
            Console.WriteLine("你剛才輸入的文字:{0}", printStr(str));
        }
    }
}

然後說下一個簡單的委託的使用流程:
1 聲明一個委託(注意,該委託傳回型別和參數列表必須和要委託的函數的傳回型別和參數列表完全一致)
例如:delegate double processDelagate(double pra1,double pra2)

2 聲明委託後,就可以定義一個該委託類型的變數
例如:processDelagate process

3 接著初始化這個委託變數為與委託有相同簽名(即傳回型別和參數列表一致)的函數引用
例如:process = new processDelagate(Multiply)
附:Multiply函數的內容
        static double Multiply(double pra1,double pra2)
        {
            return pra1 * pra2;
        }
注意:該函數和第一步聲明的委託的參數類型和參數個數是一致的

4 最後,可以使用委託變數調用這個函數,就像該變數是一個函數一樣
例如:process(1.2, 2.3)

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.