25.委托(2)
1. 上节是用静态方法声明的委托,本节是用动态方法声明委托,使之更灵活。
代码
namespace _25.委托_2_
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Man xw = new Man("小王");
Man xl = new Man("小李");
Man xz = new Man("小赵");
EatDelegate a = new EatDelegate(xw.eat);
EatDelegate s = new EatDelegate(xl.eat);
EatDelegate d = new EatDelegate(xz.eat);
EatDelegate eatChain = null;
MessageBox.Show("三人开Part");
eatChain = a + s + d;
eatChain ("西瓜");
}
}
delegate void EatDelegate(string food);
class Man
{
private string name;
public Man(string name)
{
this.name = name;
}
public void eat(string food)
{
MessageBox.Show(name + "吃" + food);
}
}
}
2. 接着上面的,传有多个参数的。
代码
namespace _25.委托_2_
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Man xw = new Man("小王");
Man xl = new Man("小李");
Man xz = new Man("小赵");
EatDelegate a = new EatDelegate(xw.eat);
EatDelegate s = new EatDelegate(xl.eat);
EatDelegate d = new EatDelegate(xz.eat);
EatDelegate eatChain = null;
MessageBox.Show("三人开Part");
eatTogether("西瓜" , a , s , d);
MessageBox.Show("xw goes out");
eatTogether("葡萄" ,s , d);
MessageBox.Show("xw comes here");
eatTogether("橘子" ,a , s,d);
eatTogether(null, null);
}
static void eatTogether (string food, params EatDelegate [] values)
{
if (values == null)
{
MessageBox.Show("Party is over !");
}
else
{
EatDelegate eatChain = null;
foreach (EatDelegate ed in values)
eatChain += ed;
eatChain(food);
MessageBox.Show("");
}
}
}
delegate void EatDelegate(string food);
class Man
{
private string name;
public Man(string name)
{
this.name = name;
}
public void eat(string food)
{
MessageBox.Show(name + "吃" + food);
}
}
}