private delegate void Example2();
private void btnExample2_Click(object sender, EventArgs e)
{
string firstName = "Zach", lastName = "Smith";
Example2 ex = new Example2(delegate()
{
MessageBox.Show(firstName + " " + lastName);
});
ex();
}
匿名方法可存取外部變數(firstName, lastName),但自身宣告的變數不外洩。注意:匿名方法無法存取 ref/out 參數。
private delegate void Example3(string firstName, string lastName);
private void btnExample3_Click(object sender, EventArgs e)
{
string p1 = "Zach", p2 = "Smith";
Example3 ex = new Example3(delegate(string fn, string ln)
{
MessageBox.Show("Example3: " + fn + " " + ln);
});
ex(p1, p2);
}
委托參數列表需與匿名方法宣告一致,呼叫時傳入實際引數。