欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

C# this关键字的四种用法

时间:2021-05-24 08:48:52|栏目:.NET代码|点击:

本文实例为大家分享了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#实现矩阵转置的方法

栏    目:.NET代码

下一篇:先装VS再装IIS时出错的解决方法

本文标题:C# this关键字的四种用法

本文地址:http://www.codeinn.net/misctech/127679.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有