当前位置: 移动技术网 > IT编程>开发语言>c# > C# this关键字的四种用法

C# this关键字的四种用法

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了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();
      }
    }
  }
}

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网