
<p>通過使用 delegate 類,委托執行個體可以封裝屬于可調用實體的方法。</p><p>對于執行個體方法,委托由一個包含類的執行個體和該執行個體上的方法組成。</p><p>對于靜态方法,可調用實體由一個類和該類上的靜态方法組成。</p><p>是以,委托可用于調用任何對象的函數,而且委托是面向對象的、類型安全的。</p><p>定義和使用委托有三個步驟:</p>
聲明
執行個體化
調用


<p><span style="color: #ff00ff;">c#可通過使用委托來确定在運作時選擇要調用哪些函數。</span></p>

以下代碼示範了委托的建立、執行個體化和調用:
c# 複制代碼
public class mathclass
{
public static long add(int i, int j) // static
{
return (i + j);
}
public static long multiply (int i, int j) // static
return (i * j);
}
class testmathclass
delegate long del(int i, int j); // declare the delegate type
static void main()
del operation; // declare the delegate variable
operation = mathclass.add; // set the delegate to refer to the add method
long sum = operation(11, 22); // use the delegate to call the add method
operation = mathclass.multiply; // change the delegate to refer to the multiply method
long product = operation(30, 40); // use the delegate to call the multiply method
system.console.writeline("11 + 22 = " + sum);
system.console.writeline("30 * 40 = " + product);
輸出
11 + 22 = 33
30 * 40 = 1200