例2——變量范圍
任何在匿名方法裡聲明的變量的范圍都不會超出匿名方法的代碼塊。但是,匿名方法確實具有訪問它們代碼塊之外的變量的能力,只要這些變量在匿名方法所使用的范圍裡。這些變量被微軟稱為外部變量。下面示例2顯示了匿名方法如何引用外部變量:
示例列表2
#region Variable scope example - Example2
private delegate void Example2();
privatevoid btnExample2_Click(object sender, EventArgs e)
{
//Setup our parameters.
string firstName = "Zach";
string lastName = "Smith";
//Create an instance of the Example2 delegate with an
// anonymous method.
Example2 example =
newExample2(
delegate() {
MessageBox.Show(firstName " " lastName);
});
//Execute the delegate.
example();
}
#endregion
要注意的是,根據MSDN的文檔,匿名方法裡的ref和out參數無法被訪問到。
例3——參數的傳遞
你可以將參數傳遞給匿名方法,方式就和你處理引用命名方法參數的委托一樣。下面的示例3說明這種類型的功能:
示例列表3
#region Parameter example - Example3
private delegate void Example3(string firstName, string lastName);
privatevoid btnExample3_Click(object sender, EventArgs e)
{
//Setup our parameters.
string parameter1 = "Zach";
string parameter2 = "Smith";
//Create an instance of the Example3 delegate with an
// anonymous method.
Example3 example =
newExample3(
delegate(string firstName, string lastName)
{
MessageBox.Show("Example3: " firstName " " lastName);
});
//Execute the delegate.
example(parameter1, parameter2);
}
#endregion