本帖最后由 郑朝明 于 2013-1-23 19:16 编辑
来个老鸟总结下。万分感谢!
using System;
delegate void Eatdelegate(string food);//定义Eatdelegate
class Man
{
private string name;
public Man(string name)//构造方法对name赋值
{
this.name=name;
}
private void eat(string food)//吃的方法
{
Console.WriteLine(name + "吃" + food);
}
}
class party
{
static void eatToghter(string food, params Eatdelegate[] values)//动态调用委托链的eatToghter方法
{
if (values == null)
{
Console.WriteLine("party结束");
}
else
{
Eatdelegate eatChain=null;//声明委托链
foreach(Eatdelegate ed in values)//对委托链赋值
eatChain+=ed;
eatChain(food);//实现委托链
Console.WriteLine();
}
}
static void Main()
{
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("张三、李四、王五开party");
eatToghter("香蕉",zs,ls,ww); //委托作为参数传递给eatToghter方法
Console.WriteLine("李四上出去接电话");
eatToghter("桔子",zs ,ww);
Console.WriteLine("李四回来了");
eatToghter("西瓜",zs,ls,ww);
eatToghter("",null);
Console.ReadKey();
}
} |