如何在 C# 中例項化委託?
使用 new 關鍵字來例項化委託。建立委託時,傳遞給 new 表示式引數的格式應類似於方法呼叫,但無需傳遞方法引數。
例如 -
public delegate void printString(string s); printString ps1 = new printString(WriteToScreen);
你也可以使用匿名方法來例項化一個委託 -
//declare
delegate void Del(string str);
Del d = delegate(string name) {
Console.WriteLine("Notification received for: {0}", name);
};我們來看一個宣告並例項化委託的示例 -
示例
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl {
class TestDelegate {
static int num = 10;
public static int AddNum(int p) {
num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}輸出
Value of Num: 35 Value of Num: 175
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP