C# 中this保留字的作用是什么

2023-06-09

这期内容当中小编将会给大家带来有关C# 中this保留字的作用是什么,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

C#语言有很多值得学习的地方,这里我们主要介绍C# this保留字,包括介绍在结构的方法中出现表示对调用该方法的结果的引用等方面。

this 是一个保留字,仅限于构造函数和方法成员中使用;

在类的构造函数中出现表示对正在构造的对象本身的引用,在类的方法中出现表示对调用该方法的对象的引用,在结构的构造上函数中出现表示对正在构造的结构的引用,在结构的方法中出现表示对调用该方法的结果的引用;

C# this保留字不能用于静态成员的实现里,因为这时对象或结构并未实例化;

在 C# 系统中,this 实际上是一个常量,所以不能使用 this++ 这样的运算;

C# this保留字一般用于限定同名的隐藏成员、将对象本身做为参数、声明索引访问器、判断传入参数的对象是否为本身。

示例:

  1. using System;  

  2. using System.Collections.Generic;  

  3. using System.Text;  

  4.    

  5. namespace Example10  

  6. {  

  7. class Class1  

  8. {  

  9. private double c;  

  10. private string value;  

  11.    

  12. public double C  

  13. {  

  14. get  

  15. {  

  16. return c;  

  17. }  

  18. }  

  19. public Class1(double c)  

  20. {  

  21. //限定同名的隐藏成员  

  22. this.c = c;  

  23. }  

  24. public Class1(Class1 value)  

  25. {  

  26. //用对象本身实例化自己没有意义  

  27. if (this != value)  

  28. {  

  29. c = value.C;  

  30. }  

  31. }  

  32. public override string ToString()  

  33. {  

  34. //将对象本身做为参数  

  35. return string.Format("{0} Celsius = {1} Fahrenheit", 
    c, UnitTransClass.C2F(this));  

  36. }  

  37.    

  38. //由于好奇,在这做了一个效率测试,想看看到底哪种方式访问成员变量更快,
    结论:区别不大。。。  

  39. public string Test1()  

  40. {  

  41. long vTickCount = Environment.TickCount;  

  42. for (int i = 0; i < 10000000; i++)  

  43. this.value = i.ToString();  

  44. return string.Format("Have this.: {0} MSEL", 
    Environment.TickCount - vTickCount);  

  45. }  

  46. public string Test2()  

  47. {  

  48. long vTickCount = Environment.TickCount;  

  49. for (int i = 0; i < 10000000; i++)  

  50. value = i.ToString();  

  51. return string.Format("Don't have this.: {0} MSEL", 
    Environment.TickCount - vTickCount);  

  52. }  

  53. }  

  54. class UnitTransClass  

  55. {  

  56. public static double C2F(Class1 value)  

  57. {  

  58. //摄氏到华氏的转换公式  

  59. return 1.8 * value.C + 32;  

  60. }  

  61. }  

  62. class Program  

  63. {  

  64. static void Main(string[] args)  

  65. {  

  66. Class1 tmpObj = new Class1(37.5);  

  67. Console.WriteLine(tmpObj);  

  68. Console.WriteLine(tmpObj.Test1());  

  69. Console.WriteLine(tmpObj.Test2());  

  70. Console.ReadLine();  

  71. }  

  72. }  

上述就是小编为大家分享的C# 中this保留字的作用是什么了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注本站行业资讯频道。

《C# 中this保留字的作用是什么.doc》

下载本文的Word格式文档,以方便收藏与打印。