委託(delegate)
1. 相當於C語言的函數指針,執行委託,就是執行相應代理的方法.
2. 使用委託的步驟
a. 聲明委託類型(delegate)
委託的簽名決定了委託可以代理的方法的類型,方法的簽名要去委託的簽名一致
例:delegate void StringProcessor (string input);
b. 定義要執行的方法
以下5個方法中,只有第1個跟最後一個方法的簽名與委託一致,纔可以被委託調用。
void PrintString (string x) void PrintInteger (int x) void PrintTwoStrings (string x, string y) int GetStringLength (string x) //返回值不一樣也不行
void PrintObject (object x) //object是string的基類
c. 創建委託對象
StringProcessor proc1, proc2; proc1 = new StringProcessor(StaticMethods.PrintString); //指向一類方法 InstanceMethods instance = new InstanceMethods(); proc2 = new StringProcessor(instance.PrintString); //指向一實例方法
d. 調用執行委託對象
每個委託對象都有個Invoke(參數)方法去執行委託,
但是也可以把委託對象就看作是個方法,直接執行
3. 示例
using System; delegate void StringProcessor(string input); class Person { string name; public Person(string name) { this.name = name; } public void Say(string message) { Console.writeLine ("{0} says: {1}", name, message); } } class Background { public static void Note(string note) { Console.writeLine ("({0})", note); } } class SimpleDelegateUse { static void Main() { Person jon = new Person("Jon"); Person tom = new Person("Tom"); StringProcessor jonsVoice, tomsVoice, background; jonsVoice = new StringProcessor(jon.Say); tomsVoice = new StringProcessor(tom.Say); background = new StringProcessor(Background.Note); jonsVoice("Hello, son."); tomsVoice.Invoke("Hello, Daddy!"); background("An airplane flies past."); } }
4. 委託的合併與刪除(Combining and removing delegates)
一個委託可以代理一個方法,其實也可以代理很多的方法,通過合併操作,可以合併多個委託構成一個 代理列表(invocation list), 這樣執行該委託就可以執行列表裏的一序列方法。同理,可以從這個列表裏刪除某一委託,就是刪除代理的某一方法。
委託具有不變性,跟字符串的不變性一樣,一旦創建了個委託對象就不可改變該委託,委託的合併與刪除都會返回一個新的委託
合併的方法: Delegate.Combine(x,y) 簡寫 + 或 +=
刪除的方法: Delegate.Remove(source,value) 簡寫 - 或 -=
5. 委託一般不單獨使用,一般用在事件裏
事件並不是委託的實例,是Add/Remove方法對,相當於屬性的getters/settters