溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C#匿名方法怎么用

發(fā)布時(shí)間:2021-12-01 13:49:39 來源:億速云 閱讀:142 作者:小新 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)C#匿名方法怎么用,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

C#匿名方法

這是對(duì)變量范圍的擴(kuò)展。但是,下面例子說明了匿名參數(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ù)訪問變量的時(shí)候被反映出來。

你可能還注意到在這個(gè)實(shí)例里委托關(guān)鍵字后面沒有括號(hào)。當(dāng)C#匿名方法不需要帶參數(shù)的時(shí)候,后面的括號(hào)是可選的。

關(guān)于“C#匿名方法怎么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI