在C#
你可以把匿名方法想象為一個實現與委托進行關聯這項功能的便捷途徑
如何使用匿名方法
多用代碼少用說教來解釋和理解匿名方法會容易一些
例
使用匿名方法很簡單
示例列表
#region Simple example
privatedelegatevoidExample
privatevoid btnExample
{
//Declare an instance of the Example
// You can see where I
// method in place of a named method
// the delegate() keyword
Example
newExample
delegate()
{
MessageBox
});
example();
}
#endregion
例
任何在匿名方法裡聲明的變量的范圍都不會超出匿名方法的代碼塊
示例列表
#region Variable scope example
privatedelegatevoidExample
privatevoid btnExample
{
//Setup our parameters
string firstName =
string lastName =
//Create an instance of the Example
// anonymous method
Example
newExample
delegate() {
MessageBox
});
//Execute the delegate
example();
}
#endregion
要注意的是
例
你可以將參數傳遞給匿名方法
示例列表
#region Parameter example
privatedelegatevoidExample
privatevoid btnExample
{
//Setup our parameters
string parameter
string parameter
//Create an instance of the Example
// anonymous method
Example
newExample
delegate(string firstName
{
MessageBox
});
//Execute the delegate
example(parameter
}
#endregion
例
就和命名方法一樣
示例列表
#region Multiple method association (stacking)
privatedelegatevoidExample
privatevoid btnExample
{
//Setup our parameters
string parameter
string parameter
//Create an instance of the Example
// anonymous method
Example
newExample
delegate(string firstName
{
MessageBox
});
//Add another method to the delegate
// a named method
example += newExample
//Execute the delegate
example(parameter
}
privatevoid Example
{
MessageBox
}
#endregion
例
就和命名方法一樣
示例列表
#region Passing anonymous methods
privatedelegatevoidExample
privatevoid btnExample
{
//Execute Passit and pass the anonymous method
Passit((Example
{
MessageBox
});
//Execute Passit with the named method
Passit(Example
}
privatevoid Example
{
MessageBox
}
privatevoid Passit(Example
{
example(
}
#endregion
例
這是對上面例
示例列表
#region Accessing class members
privatedelegatevoidExample
privateint _customerId;
privatestring _customerCode;
publicint CustomerID
{
get { return _customerId; }
set { _customerId = value; }
}
publicstring CustomerCode
{
get { return _customerCode; }
set { _customerCode = value; }
}
privatevoid btnExample
{
//Populate out properties
this
this
//Setup the delegate/anonymous method
Example
newExample
delegate
{
this
});
//Execute the delegate
example();
//Change the properties
this
this
//Execute the delegate again
// Notice that the new values are reflected
example();
}
privatevoid ShowCustomer(int customerId
{
MessageBox
String
customerId
}
#endregion
要注意的是
你可能還注意到在這個實例裡委托關鍵字後面沒有括號
評論
我希望本文已經說明如何使用匿名方法
(文/Zach Smith
From:http://tw.wingwit.com/Article/program/net/201311/13844.html