1. 程式人生 > 實用技巧 >C# 委託

C# 委託

C#委託(Delegate)

C# 中的委託(Delegate)類似於 C 或 C++ 中函式的指標。委託(Delegate)是存有對某個方法的引用的一種引用型別變數。引用可在執行時被改變。

委託(Delegate)特別用於實現事件和回撥方法。所有的委託(Delegate)都派生自System.Delegate類。

宣告委託(Delegate)

委託宣告決定了可由該委託引用的方法。委託可指向一個與其具有相同標籤的方法。

例如,假設有一個委託:

public delegate int MyDelegate (string s);

上面的委託可被用於引用任何一個帶有一個單一的string

引數的方法,並返回一個int型別變數。

宣告委託的語法如下:

delegate <return type> <delegate-name> <parameter list>

例項化委託(Delegate)

一旦聲明瞭委託型別,委託物件必須使用new關鍵字來建立,且與一個特定的方法有關。當建立委託時,傳遞到new語句的引數就像方法呼叫一樣書寫,但是不帶有引數。例如:

public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 
= new printString(WriteToFile);
 delegate string getString(string input);
        private static string result = "";
        public static string getFirst(string str)
        {
            if (!String.IsNullOrEmpty(str))
            {
                string target = str.ToCharArray()[0] + "";
                result 
+= target; return target; } return ""; } public static string getEnd(string str) { if (!String.IsNullOrEmpty(str)) { string target = str.ToCharArray()[str.Length - 1] + ""; result += target; return target; } return ""; } public static string getResult() { return result; } public static void run() { getString gs1 = new getString(getFirst); getString gs2 = new getString(getEnd); gs1("4114514"); Console.WriteLine(getResult()); gs2("114512"); Console.WriteLine(getResult()); }

委託的多播(Multicasting of a Delegate)

委託物件可使用 "+" 運算子進行合併。一個合併委託呼叫它所合併的兩個委託。只有相同型別的委託可被合併。"-" 運算子可用於從合併的委託中移除元件委託。

使用委託的這個有用的特點,您可以建立一個委託被呼叫時要呼叫的方法的呼叫列表。這被稱為委託的多播(multicasting),也叫組播。

 getString gs;
            getString gs1 = new getString(getFirst);
            getString gs2 = new getString(getEnd);
            gs = gs1 + gs2;//多播
            gs("41145142");
            Console.WriteLine(getResult());

delegate string getString(string input);
        public delegate void toDo(String msg);
       
        public static void writeLine(string msg)
        {
            Console.WriteLine(msg);
        }
        public static void writeAgain(string msg)
        {
            Console.WriteLine(msg);
            Console.WriteLine(msg);
        }
        public static void execute(toDo todo)
        {
            //實現委託
            todo("Hello World.");
        }
        public static void run()
        {
            toDo td = new toDo(writeLine);
            toDo td1 = new toDo(writeAgain);
            execute(td);
            execute(td1);

        }
    }