照着书上的例子写了个简单的委托实现
class Program
{
public static void Add(int x, int y)
{
Console.WriteLine("x+y=" + (x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("x-y=" + (x - y));
}
// 声明一个委托
public delegate void Com(int x, int y);
static void Main(string[] args)
{
// 进行委托绑定
Com c1 = new Com(Add);
c1 += new Com(Sub);// 委托链的绑定
// 执行委托的回调方法
c1(4, 3);
Console.ReadLine();
// 输出x+y=7 x-y=1
// 匿名方法使用委托
Com c2 = delegate(int x, int y) {// 省去了单独定义x*y的方法!
Console.WriteLine("x*y=" + (x * y));
};
c2(5, 6);
Console.ReadLine();
}
}