C# this关键字的四种用法
本文实例为大家分享了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(); } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
栏 目:C#教程
下一篇:C#使用第三方组件生成二维码汇总
本文标题:C# this关键字的四种用法
本文地址:https://www.xiuzhanwang.com/a1/C_jiaocheng/6132.html
您可能感兴趣的文章
- 01-10C#通过反射获取当前工程中所有窗体并打开的方法
- 01-10关于ASP网页无法打开的解决方案
- 01-10WinForm限制窗体不能移到屏幕外的方法
- 01-10WinForm绘制圆角的方法
- 01-10C#停止线程的方法
- 01-10WinForm实现仿视频播放器左下角滚动新闻效果的方法
- 01-10C#通过重写Panel改变边框颜色与宽度的方法
- 01-10C#实现清空回收站的方法
- 01-10C#实现读取注册表监控当前操作系统已安装软件变化的方法
- 01-10C#实现多线程下载文件的方法
阅读排行
本栏相关
- 01-10C#通过反射获取当前工程中所有窗体并
- 01-10关于ASP网页无法打开的解决方案
- 01-10WinForm限制窗体不能移到屏幕外的方法
- 01-10WinForm绘制圆角的方法
- 01-10C#实现txt定位指定行完整实例
- 01-10WinForm实现仿视频播放器左下角滚动新
- 01-10C#停止线程的方法
- 01-10C#实现清空回收站的方法
- 01-10C#通过重写Panel改变边框颜色与宽度的
- 01-10C#实现读取注册表监控当前操作系统已
随机阅读
- 01-10SublimeText编译C开发环境设置
- 01-10delphi制作wav文件的方法
- 01-11Mac OSX 打开原生自带读写NTFS功能(图文
- 04-02jquery与jsp,用jquery
- 01-10使用C语言求解扑克牌的顺子及n个骰子
- 08-05dedecms(织梦)副栏目数量限制代码修改
- 08-05织梦dedecms什么时候用栏目交叉功能?
- 01-11ajax实现页面的局部加载
- 08-05DEDE织梦data目录下的sessions文件夹有什
- 01-10C#中split用法实例总结