这里介绍C# this关键字,由于静态成员函数存在于类一级,并且不是对象的一部分,因此没有this指针。在静态方法中引用C# this关键字是错误的。

C# this关键字引证类的当时实例。

C# this关键字介绍(C#this关键字)  this关键字 第1张

以下是 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. publicEmployee(stringname,intage)
  10. {
  11. //运用this限制字段,name与age
  12. this._name=name;
  13. this._age=age;
  14. }
  15. publicstringName
  16. {
  17. get{returnthis._name;}
  18. }
  19. publicintAge
  20. {
  21. get{returnthis._age;}
  22. }
  23. //打印雇员材料
  24. publicvoidPrintEmployee()
  25. {
  26. //将Employee目标作为参数传递到DoPrint办法
  27. Print.DoPrint(this);
  28. }
  29. //声明索引器
  30. publicstringthis[intparam]
  31. {
  32. get{return_arr[param];}
  33. set{_arr[param]=value;}
  34. }
  35. }
  36. classPrint
  37. {
  38. publicstaticvoidDoPrint(Employeee)
  39. {
  40. Console.WriteLine("Name:{0}\nAge:{1}",e.Name,e.Age);
  41. }
  42. }
  43. classTestApp
  44. {
  45. staticvoidMain()
  46. {
  47. EmployeeE=newEmployee("Hunts",21);
  48. E[0]="Scott";
  49. E[1]="Leigh";
  50. E[4]="Kiwis";
  51. E.PrintEmployee();
  52. for(inti=0;i<5;i++)
  53. {
  54. Console.WriteLine("FriendsName:{0}",E[i]);
  55. }
  56. Console.ReadLine();
  57. }
  58. }
  59. /**//*
  60. 控制台输出:
  61. Name:Hunts
  62. Age:21
  63. FriendsName:Scott
  64. FriendsName:Leigh
  65. FriendsName:
  66. FriendsName:
  67. FriendsName:Kiwis
  68. */

因为静态成员函数存在于类一级,而且不是目标的一部分,因而没有this指针。在静态办法中引证C# this关键字是过错的。索引器答应类或结构的实例依照与数组相同的办法进行索引。索引器类似于特点,不同之处在于它们的拜访器选用参数。

【修改引荐】

  1. 如何用C#和ADO.NET拜访
  2. 浅析C# Switch句子
  3. C#验证输入办法详解
  4. 简略介绍C# 匿名办法
  5. C# FileSystemWatcher目标
转载请说明出处
知优网 » C# this关键字介绍(C#this关键字)

发表评论

您需要后才能发表评论