C# this关键字引用类的当前实例。

来源:互联网 发布:网络生存游戏 编辑:程序博客网 时间:2024/05/24 00:28


    以下是 this 的常用用途:
    ◆限定被相似的名称隐藏的成员
    ◆将对象作为参数传递到其他方法
    ◆声明索引器

    C# this关键字示例:

  1. //this关键字  
  2. //keywords_this.cs  
  3. usingSystem;  
  4. classEmployee  
  5. {  
  6. privatestring_name;  
  7. privateint_age;  
  8. privatestring[]_arr=newstring[5];  
  9.  
  10. publicEmployee(stringname,intage)  
  11. {  
  12. //使用this限定字段,name与age  
  13. this._name=name;  
  14. this._age=age;  
  15. }  
  16.  
  17. publicstringName  
  18. {  
  19. get{returnthis._name;}  
  20. }  
  21.  
  22. publicintAge  
  23. {  
  24. get{returnthis._age;}  
  25. }  
  26.  
  27. //打印雇员资料  
  28. publicvoidPrintEmployee()  
  29. {  
  30. //将Employee对象作为参数传递到DoPrint方法  
  31. Print.DoPrint(this);  
  32. }  
  33.  
  34. //声明索引器  
  35. publicstringthis[intparam]  
  36. {  
  37. get{return_arr[param];}  
  38. set{_arr[param]=value;}  
  39. }  
  40.  
  41. }  
  42. classPrint  
  43. {  
  44. publicstaticvoidDoPrint(Employeee)  
  45. {  
  46. Console.WriteLine("Name:{0}\nAge:{1}",e.Name,e.Age);  
  47. }  
  48. }  
  49.  
  50. classTestApp  
  51. {  
  52. staticvoidMain()  
  53. {  
  54. EmployeeE=newEmployee("Hunts",21);  
  55. E[0]="Scott";  
  56. E[1]="Leigh";  
  57. E[4]="Kiwis";  
  58. E.PrintEmployee();  
  59.  
  60. for(inti=0;i<5;i++)  
  61. {  
  62. Console.WriteLine("FriendsName:{0}",E[i]);  
  63. }  
  64.  
  65. Console.ReadLine();  
  66. }  
  67. }  
  68.  
  69. /**//*  
  70. 控制台输出:  
  71. Name:Hunts  
  72. Age:21  
  73. FriendsName:Scott  
  74. FriendsName:Leigh  
  75. FriendsName:  
  76. FriendsName:  
  77. FriendsName:Kiwis  
  78. */ 

    由于静态成员函数存在于类一级,并且不是对象的一部分,因此没有this指针。在静态方法中引用C# this关键字是错误的。索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。


原创粉丝点击