C# this关键字的四种用法

时间:2021-05-19

本文实例为大家分享了C# this关键字的四种用法,供大家参考,具体内容如下

用法一this代表当前实例,用this.显式调用一个类的方法和成员

namespace Demo{ public class Test { private string scope = "全局变量"; public string getResult() { string scope = "局部变量";       // 在这里,this代表Test的实例,所以this.scope指向的是全局变量,scope所访问的是局部变量 return this.scope + "-" + scope; } } class Program { static void Main(string[] args) { try { Test test = new Test(); Console.WriteLine(test.getResult()); } catch (Exception ex) { Console.WriteLine(ex); } finally { Console.ReadLine(); } } }

用法二通过this实现原始类型的扩展(下一篇详解)

用法三通过this实现索引器,可用于优化程序性能(下一篇详解)

用法四用this串联构造函数

namespace Demo{ public class Test { public Test() { Console.WriteLine("无参构造函数"); } // 这里的this()指向的是Test()无参构造函数 // 相当于继承了无参构造函数 public Test(string text) : this() { // 程序进来后会先执行Test()无参函数,然后继续往下边执行 Console.WriteLine(text); Console.WriteLine("有参构造函数"); } } class Program { static void Main(string[] args) { try { Test test = new Test("张三"); } catch (Exception ex) { Console.WriteLine(ex); } finally { Console.ReadLine(); } } }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章