程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 充分利用C#匿名方法的平台優勢(4)

充分利用C#匿名方法的平台優勢(4)

編輯:關於C語言

例5——將匿名方法作為參數傳遞

就和命名方法一樣,將匿名方法作為參數傳遞給函數是可能的。這並不是一個我認為會通常使用的特性,但是我敢肯定未來會有這種需要。下面的代碼(例5)說明了這種類型的功能,它將一個命名方法作為參數傳遞給了函數:

示例列表5

#region Passing anonymous methods - Example5
private delegate void Example5(string firstName, string lastName);
privatevoid btnExample5_Click(object sender, EventArgs e)
{
//Execute Passit and pass the anonymous method.
Passit((Example5)delegate(string firstName, string lastName)
{
MessageBox.Show("Example5: " firstName " " lastName);
});
//Execute Passit with the named method.
Passit(Example5NamedMethod);
}
privatevoid Example5NamedMethod(string firstName, string lastName)
{
MessageBox.Show("Example5Method: " firstName " " lastName);
}
privatevoid Passit(Example5 example)
{
example("Zach", "Smith");
}
#endregion

例6—-訪問類成員

這是對上面例2的變量范圍的擴展。但是,這個例子(例6)說明了匿名參數還能夠在它們的代碼塊之外執行命名方法:

示例列表6

#region Accessing class members - Example6
private delegate void Example6();
privateint _customerId;
privatestring _customerCode;
publicint CustomerID
{
get { return _customerId; }
set { _customerId = value; }
}
publicstring CustomerCode
{
get { return _customerCode; }
set { _customerCode = value; }
}
privatevoid btnExample6_Click(object sender, EventArgs e)
{
//Populate out propertIEs.
this.CustomerID = 90;
this.CustomerCode = "1337HK";
//Setup the delegate/anonymous method.
Example6 example =
newExample6(
delegate
{
this.ShowCustomer(this.CustomerID, this.CustomerCode);
});
//Execute the delegate.
example();
//Change the propertIEs.
this.CustomerID = 54;
this.CustomerCode = "L4M3";
//Execute the delegate again.
// Notice that the new values are reflected.
example();
}
privatevoid ShowCustomer(int customerId, string customerCode)
{
MessageBox.Show(
String.Format("CustomerID: {0}nCustomer Code: {1}",
customerId, customerCode));
}
#endregion

要注意的是,我兩次調用了與匿名方法相關聯的委托。你可能會發現一個很有趣的事情:在這些調用中,方法會輸出兩組不同的值。這是因為用在匿名方法裡的外部變量在創建匿名方法的時候被引用。這意味著對這些變量的任何更改都會在匿名函數訪問變量的時候被反映出來。

你可能還注意到在這個實例裡委托關鍵字後面沒有括號。當匿名方法不需要帶參數的時候,後面的括號是可選的。

評論

我希望本文已經說明如何使用匿名方法。雖然它們還不是革命性的,但是它們是C#演化成為一門程序員友好的語言過程中的一個重要步驟。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved