C#匿名方法詳細剖析
作者:佚名
這里介紹在C#匿名方法里的外部變量在創建C#匿名方法的時候被引用。這意味著對這些變量的任何更改都會在匿名函數訪問變量的時候被反映出來。
C#語言還是比較常見的東西,這里我們主要介紹C#匿名方法,包括介紹當C#匿名方法不需要帶參數的時候,后面的括號是可選的等方面。
C#匿名方法
這是對變量范圍的擴展。但是,下面例子說明了匿名參數還能夠在它們的代碼塊之外執行命名方法:
- privatedelegatevoidExample6();
- 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: Customer Code: ",
- customerId, customerCode));
- }
要注意的是,我兩次調用了與C#匿名方法相關聯的委托。你可能會發現一個很有趣的事情:在這些調用中,方法會輸出兩組不同的值。這是因為用在C#匿名方法里的外部變量在創建C#匿名方法的時候被引用。這意味著對這些變量的任何更改都會在匿名函數訪問變量的時候被反映出來。
你可能還注意到在這個實例里委托關鍵字后面沒有括號。當C#匿名方法不需要帶參數的時候,后面的括號是可選的。
【編輯推薦】
責任編輯:佚名
來源:
cnblogs