之前已经介绍过委托链,下面这个是关于委托链的拓展。
using System;
namespace DelegateTest
{
delegate void EatDelegate(string food);
class Party
{
//声明一个参数可变的方法
static void eatToghter(string food, params EatDelegate[] values)
{
if (values == null)
{
Console.WriteLine("座谈会结束");
}
else
{
//声明委托链
EatDelegate eatChain = null;
//将委托链接起来
foreach (EatDelegate ed in values)
{
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);
Console.WriteLine("张三,李四,王五开座谈会");
eatToghter("西瓜", zs, ls, ww);
Console.WriteLine("李四出去接电话");
eatToghter("香蕉", zs, ww);
Console.WriteLine("李四回来了");
eatToghter("桔子", zs, ls, ww);
eatToghter(null, null);
Console.ReadKey();
}
}
//产生人类
class Man
{
private string name;
public Man(string name)
{
this.name = name;
}
public void eat(string food)
{
Console.WriteLine(name + "吃" + food);
}
}
}
效果如下: