C# this關(guān)鍵字介紹
作者:佚名
這里介紹C# this關(guān)鍵字,由于靜態(tài)成員函數(shù)存在于類一級,并且不是對象的一部分,因此沒有this指針。在靜態(tài)方法中引用C# this關(guān)鍵字是錯(cuò)誤的。
C# this關(guān)鍵字引用類的當(dāng)前實(shí)例。
以下是 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ù)。
【編輯推薦】
責(zé)任編輯:佚名
來源:
博客園