溫馨提示×

溫馨提示×

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

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

C# 中this關(guān)鍵字的作用是什么

發(fā)布時(shí)間:2021-07-07 16:46:36 來源:億速云 閱讀:314 作者:Leah 欄目:編程語言

這篇文章給大家介紹C# 中this關(guān)鍵字的作用是什么,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

以下是 this 的常用用途:
◆限定被相似的名稱隱藏的成員
◆將對象作為參數(shù)傳遞到其他方法
◆聲明索引器

C# this關(guān)鍵字示例:

//this關(guān)鍵字  //keywords_this.cs  usingSystem;  classEmployee  {  privatestring_name;  privateint_age;  privatestring[]_arr=newstring[5];   publicEmployee(stringname,intage)  {  //使用this限定字段,name與age  this._name=name;  this._age=age;  }   publicstringName  {  get{returnthis._name;}  }   publicintAge  {  get{returnthis._age;}  }   //打印雇員資料  publicvoidPrintEmployee()  {  //將Employee對象作為參數(shù)傳遞到DoPrint方法  Print.DoPrint(this);  }   //聲明索引器  publicstringthis[intparam]  {  get{return_arr[param];}  set{_arr[param]=value;}  }   }  classPrint  {  publicstaticvoidDoPrint(Employeee)  {  Console.WriteLine("Name:{0}\nAge:{1}",e.Name,e.Age);  }  }   classTestApp  {  staticvoidMain()  {  EmployeeE=newEmployee("Hunts",21);  E[0]="Scott";  E[1]="Leigh";  E[4]="Kiwis";  E.PrintEmployee();   for(inti=0;i<5;i++)  {  Console.WriteLine("FriendsName:{0}",E[i]);  }   Console.ReadLine();  }  }   /**//*  控制臺輸出:  Name:Hunts  Age:21  FriendsName:Scott  FriendsName:Leigh  FriendsName:  FriendsName:  FriendsName:Kiwis  */

由于靜態(tài)成員函數(shù)存在于類一級,并且不是對象的一部分,因此沒有this指針。在靜態(tài)方法中引用C# this關(guān)鍵字是錯(cuò)誤的。索引器允許類或結(jié)構(gòu)的實(shí)例按照與數(shù)組相同的方式進(jìn)行索引。索引器類似于屬性,不同之處在于它們的訪問器采用參數(shù)。

關(guān)于C# 中this關(guān)鍵字的作用是什么就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

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

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

AI