namespace delegate01
{
delegate void Playball(string ball); //定义一个委托
class Person //声明一个类
{
private string name;
public Person(string Name) //构造函数
{
this.name = Name;
}
public void play(string ball) //在类中声明一个方法,参数类型与委托一致
{
Console.WriteLine(name+" play "+ball );
}
}
class Sport //声明第二个类
{
public void appb(string ball, params Playball[] pss) //在类中声明一个方法
{
if (pss == null)
{
Console.WriteLine("座谈会结束");
}
else
{
Playball ppb = null; //实例化一个空的委托
foreach (Playball ps in pss) //将方法参数中的委托数组添加到空委托中,统一传入参数
{
ppb += ps;
}
ppb(ball);
Console.WriteLine();
}
}
}
class Program
{
static void Main(string[] args)
{
Person zs = new Person("zhang san"); //实例化三个类的实例
Person ls = new Person("li si");
Person ww = new Person("wang wu");
Playball zsp = new Playball(zs.play); //实例化三个委托,分别指向三个实例的方法
Playball lsp = new Playball(ls.play);
Playball wwp = new Playball(ww.play);
Sport sport = new Sport(); //实例化第二个类
sport.appb("basketball", zsp, lsp, wwp); //将委托导入到第二个类中,其实委托就像一个指针,将方法赋给需要引用的对象
sport.appb("basketball",null);
Console.ReadKey();
}
}
} |