C# this关键字 C# this关键字的四种用法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C# this关键字 C# this关键字的四种用法

天碼亦行空   2021-03-22 我要评论
想了解C# this关键字的四种用法的相关内容吗,天碼亦行空在本文为您仔细讲解C# this关键字的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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();
      }
    }
  }
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们