如何在 C# 中宣告和例項化委託?
C# 委託與 C 或 C++ 中指向函式類似。委託是一個引用型別變數,持有一個方法的引用。引用可以在執行時被改變。
宣告委託的語法 −
delegate <return type> <delegate-name> <parameter list>
現在,讓我們看看如何例項化 C# 中的委託。
宣告委託型別後,必須使用 new 關鍵字建立一個委託物件,並將其與一個特定的方法關聯。建立委託時,傳遞給 new 表示式的引數的寫法類似於方法呼叫,但是沒有方法的引數。
public delegate void printString(string s); ... printString ps1 = new printString(WriteToScreen); printString ps2 = new printString(WriteToFile);
以下是 C# 中宣告和例項化委託的一個示例 −
示例
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