原文地址:Delegates and Events in C# / .NET
委託(Delegates)
C#中的委託類似於C/C++的指標功能。使用委託可以讓程式員在委派物件裡傳引用給方法。委派物件被傳遞給調用引用方法的代碼,而不是在編譯的時候調用方法。
直接調用方法 - 不使用委託
在大多數的情況下,當我們需要調用方法的時候,我們直接調用指定的方法。如果有個類MyClass的方法Process,我們通常用這個方法調用(SimpleSample.cs):
1using System;
2
3namespace Akadia.NoDelegate
4{
5 public class MyClass
6 {
7 public void Process()
8 {
9 Console.WriteLine("Process() begin");
10 Console.WriteLine("Process() end");
11 }
12 }
13
14 public class Test
15 {
16 static void Main(string[] args)
17 {
18 MyClass myClass = new MyClass();
19 myClass.Process();
20 }
21 }
22}
在多數情況下是沒有問題的。但是有時候,我們不想直接調用方法,更願意能傳到其他地方,以至於能夠調用。當使用者點擊按鈕等情況下,我想執行一些代碼的情況發生時,類似GUI等事件驅動的系統,委託就相當有用。
非常簡單的委託
委託的一個有趣而有用的屬性,它不需要知道或關心它所引用的類的對象。任何的對象將能做到,問題在於方法的參數類型和傳回值類型需要和委託的參數類型和傳回值類型匹配。這使得委託能完美的適用於“匿名”調用。
單播委託的語句格式如下:
delegate result-type identifier ([parameters]);
where:
result-type: The result type, which matches the return type of the function.
identifier: The delegate name.
parameters: The Parameters, that the function takes.
例如:
public delegate void SimpleDelegate () 這個申明定義了名為SimpleDelegate的委託,能夠傳任何沒有參數和傳回值的方法。 |
public delegate int ButtonClickHandler (object obj1, object obj2) 這個申明定義了名為ButtonClickHandler的委託,能夠傳任何含有兩個對象和傳回值為整型的方法。 |
待續。。。