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