1. In the previous section, the delegate is declared using static methods. In this section, the delegate is declared using dynamic methods to make it more flexible.
Code
Namespace _ 25. Delegate _ 2 _
{
Public partial class Form1: Form
{
Public Form1 ()
{
InitializeComponent ();
}
Private void Form1_Load (object sender, EventArgs e)
{
Man xw = new Man ("John ");
Man xl = new Man ("Xiao Li ");
Man xz = new Man ("Xiao Zhao ");
EatDelegate a = new EatDelegate (xw. eat );
EatDelegate s = new EatDelegate (xl. eat );
EatDelegate d = new EatDelegate (xz. eat );
EatDelegate eatChain = null;
MessageBox. Show ("three-person open Part ");
EatChain = a + s + d;
EatChain ("watermelon ");
}
}
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 + "eat" + food );
}
}
}
2. Next, the above contains multiple parameters.
Code
Namespace _ 25. Delegate _ 2 _
{
Public partial class Form1: Form
{
Public Form1 ()
{
InitializeComponent ();
}
Private void Form1_Load (object sender, EventArgs e)
{
Man xw = new Man ("John ");
Man xl = new Man ("Xiao Li ");
Man xz = new Man ("Xiao Zhao ");
EatDelegate a = new EatDelegate (xw. eat );
EatDelegate s = new EatDelegate (xl. eat );
EatDelegate d = new EatDelegate (xz. eat );
EatDelegate eatChain = null;
MessageBox. Show ("three-person open Part ");
EatTogether ("watermelon", a, s, d );
MessageBox. Show ("xw goes out ");
EatTogether ("grape", s, d );
MessageBox. Show ("xw comes here ");
EatTogether ("orange", 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 + "eat" + food );
}
}
}