C# this关键字

来源:互联网 发布:java如何实现增删改查 编辑:程序博客网 时间:2024/05/23 14:29


以下是 this 的常用用途:
◆限定被相似的名称隐藏的成员  (fang_tang_注:区分方法中同名的字段和形参)
◆将对象作为参数传递到其他方法 (fang_tang_注:声明类时,用this替代以后的实例名)
◆声明索引器                   (fang_tang_注:仅格式)

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
  20. {
  21. return this.name;
  22. }  
  23. }  
  24.  
  25. publicintAge  
  26. {  
  27. get
  28. {
  29. returnthis._age;
  30. }  
  31. }  
  32.  
  33. //打印雇员资料  
  34. public void PrintEmployee()  
  35. {  
  36. //将Employee对象作为参数传递到DoPrint方法  
  37. Print.DoPrint(this);  
  38. }  
  39.  
  40. //声明索引器  
  41. public string this[intparam]  
  42. {  
  43. get
  44. {
  45. return_arr[param];
  46. }  
  47. set
  48. {_arr[param]=value;
  49. }  
  50. }  
  51.  
  52. }  
  53. classPrint  
  54. {  
  55. public static void DoPrint(Employeee)  
  56. {  
  57. Console.WriteLine("Name:{0}\nAge:{1}",e.Name,e.Age);  
  58. }  
  59. }  
  60.  
  61. classTestApp  
  62. {  
  63. staticvoidMain()  
  64. {  
  65. EmployeeE=newEmployee("Hunts",21);  
  66. E[0]="Scott";  
  67. E[1]="Leigh";  
  68. E[4]="Kiwis";  
  69. E.PrintEmployee();  
  70.  
  71. for(inti=0;i<5;i++)  
  72. {  
  73. Console.WriteLine("FriendsName:{0}",E[i]);  
  74. }  
  75.  
  76. Console.ReadLine();  
  77. }  
  78. }  
  79.  
  80. /**//*  
  81. 控制台输出:  
  82. Name:Hunts  
  83. Age:21  
  84. FriendsName:Scott  
  85. FriendsName:Leigh  
  86. FriendsName:  
  87. FriendsName:  
  88. FriendsName:Kiwis  
  89. */ 

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

0 0
原创粉丝点击