using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 委托二之把代理作为方法的参数并进行动态调用
{
class Program
{
/// <summary>
/// 动态调用的委托可以数组参数的方法
/// </summary>
/// <param name="food"></param>
/// <param name="values"></param>
static void eatTogether(string food,params EatDelgate[] values)//声明一个参数委托类型的数组参数的方法
{
if (values == null)//先判断委托链是否为null
{
Console.WriteLine("座谈会结束");
}
else
{
EatDelgate eatChain = null;//声明一个委托变量,并为其赋值为null
foreach (EatDelgate 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("王五");
EatDelgate zsDe = new EatDelgate(zs.eat);//通过实例名来区分方法
EatDelgate lsDe = new EatDelgate(ls.eat);
EatDelgate wwDe = new EatDelgate(ww.eat);
Console.WriteLine("张三,李四,王五开座谈会");
//下面是你想思维,先想想使用的方法形式,然后在去考虑如何写这个方法
eatTogether("西瓜",zsDe,lsDe,wwDe);//这个方法使用四个参数,因为使用了params关键字,是可变参数
Console.WriteLine("李四出去了");
eatTogether("香蕉", zsDe, wwDe);//这个方法使用三个参数
Console.WriteLine("李四回来了");
eatTogether("桔子",zsDe,lsDe,wwDe);//这个方法使用是个参数,因此可以推断eatTogether是一个可变参数的方法
eatTogether(null, null);//因为eatTogether的两个参数string和EatDelegate都是引用类型,所以可以在方法中使用null
Console.ReadKey();
}
}
delegate void EatDelgate(string food);//声明一个委托
class man
{
private string name;//声明一个字段
public man(string name)
{
this.name = name; //通过构造函数进行赋值
}
public void eat(string food)
{
Console.WriteLine(name+"吃"+food);
}
}
}