委托的本质就是一个类,任何可以声明类的地方都可以声明委托。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace @delegate
{
delegate void EatDelegate(string food);
class program //定义一个类
{
static void zsEat(string food) //定义静态的方法
{
Console.WriteLine("张三" + food);
}
static void lsEat(string food)
{
Console.WriteLine("李四" + food);
}
static void wwEat(string food)
{
Console.WriteLine("王五" + food);
}
static void Main(string[] args)
{
EatDelegate zs = new EatDelegate(zsEat);
EatDelegate ls = new EatDelegate(lsEat);
EatDelegate ww = new EatDelegate(wwEat);
EatDelegate eatChain;
Console.WriteLine("张三、李四、王五开座谈会");
eatChain = zs + ls + ww;
eatChain("西瓜");
Console.WriteLine("李四出去接电话");
eatChain -= ls;
eatChain("香蕉");
Console.WriteLine("李四回来了");
eatChain += ls;
eatChain("桔子");
}
}
}
//上面的例子是委托对静态方法的代理,下面改为对动态方法的代理,代码如下:
namespace @delegate
{
delegate void EatDelegate(string food);
class Man //定义一个类Man
{
private string name; //定义一个字段name
public Man(string name) //构造Man函数,为了给字段name赋值
{
this.name = name;
}
public void eat(string food) //定义吃东西的方法
{
Console.WriteLine(name + "吃" + food);
}
}
class Party
{
static void eatToghter(string food, params EatDelegate[] value)
{
if (value == null)
{
Console.WriteLine("座谈会结束");
}
else
{
EatDelegate eatChain = null;
foreach (EatDelegate ed in value)
eatChain += ed;
eatChain(food);
Console.WriteLine();
}
}
static void Main(string[] args)
{
Man ZS = new Man("张三"); //实例化一个张三
Man LS = new Man("李四"); //实例化一个李四
Man WW = new Man("王五"); //实例化一个王五
EatDelegate zs = new EatDelegate(ZS.eat); //使用代理
EatDelegate ls = new EatDelegate(LS.eat);
EatDelegate ww = new EatDelegate(WW.eat);
EatDelegate eatChain = null;
Console.WriteLine("张三、李四、王五开座谈会");
eatToghter("西瓜", zs, ls, ww);
Console.WriteLine("李四出去接电话");
eatToghter("香蕉", zs, ww);
Console.WriteLine("李四回来了");
eatToghter("桔子", zs, ls, ww);
eatToghter(null, null);
}
}
}