C#匿名方法詳細(xì)剖析
C#語(yǔ)言還是比較常見(jiàn)的東西,這里我們主要介紹C#匿名方法,包括介紹當(dāng)C#匿名方法不需要帶參數(shù)的時(shí)候,后面的括號(hào)是可選的等方面。
C#匿名方法
這是對(duì)變量范圍的擴(kuò)展。但是,下面例子說(shuō)明了匿名參數(shù)還能夠在它們的代碼塊之外執(zhí)行命名方法:
- 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));
- }
要注意的是,我兩次調(diào)用了與C#匿名方法相關(guān)聯(lián)的委托。你可能會(huì)發(fā)現(xiàn)一個(gè)很有趣的事情:在這些調(diào)用中,方法會(huì)輸出兩組不同的值。這是因?yàn)橛迷贑#匿名方法里的外部變量在創(chuàng)建C#匿名方法的時(shí)候被引用。這意味著對(duì)這些變量的任何更改都會(huì)在匿名函數(shù)訪問(wèn)變量的時(shí)候被反映出來(lái)。
你可能還注意到在這個(gè)實(shí)例里委托關(guān)鍵字后面沒(méi)有括號(hào)。當(dāng)C#匿名方法不需要帶參數(shù)的時(shí)候,后面的括號(hào)是可選的。
【編輯推薦】