温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C# 中this关键字的作用是什么

发布时间:2021-07-07 16:46:36 来源:亿速云 阅读:304 作者:Leah 栏目:编程语言

这篇文章给大家介绍C# 中this关键字的作用是什么,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

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

C# this关键字示例:

//this关键字  //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对象作为参数传递到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  */

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

关于C# 中this关键字的作用是什么就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI