实例化委托
一旦声明了委托类型,委托对象必须使用 new 关键字来创建,且与一个特定的方法有关。当创建委托时,传递到 new 语句的参数就像方法调用一样书写,但是不带有参数。例如:
public delegate void printString(string s);
//...
printString ps1 = new printString(WriteToScreen);//实例化委托WriteToScreen方法
printString ps2 = new printString(WriteToFile);
实例如下:
using System;
namespace DelegateApp
{
delegate int NumberChanger(int n);
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)
{
// 创建委托实例
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
// 使用委托对象调用方法
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());// 35
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum()); //175
}
}
}