如何在 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