欢迎来到代码驿站!

.NET代码

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

C#中this的使用实例分析

时间:2021-05-06 09:41:10|栏目:.NET代码|点击:

this关键字在C#程序设计中的应用非常频繁,今天本文就this关键字的用法做一番分析,希望能提对大家的C#程序设计有一定的帮助作用。具体分析如下:

1.代表当前类,在当前类中可使用this访问当前类成员变量和方法(需要注意的是 静态方法中不能使用this),也可用于参数传递,传递当前对象的引用。

示例代码如下:

class Program
{
  static void Main(string[] args)
  {
    thisClass testObj = new thisClass();
    Console.ReadLine();
  }
}
class thisClass
{
  private string A { get; set; }
  public thisClass()
  {
    /*当前类this 访问类中属性A 静态方法无法访问A属性*/
    this.A = "Test String";
    Console.WriteLine(this.TestFun("TestFun :"));
  }
  private string TestFun(string args)
  {
    return args + this.A;
  }
}

运行结果如下图所示:

2.声明索引器

索引器:允许类和结构的实例按照与数组相同的方式进行索引,索引器类似与属性,不同之处在于他们的访问器采用参数,被称为有参属性,索引可以被重载,属于实例成员,不能声明为static。

示例代码如下:

class Program
{
  static void Main(string[] args)
  {
    indexClass intIndexClass = new indexClass();
    intIndexClass[0] = new thisClass("intIndexClass 111");
    intIndexClass[1] = new thisClass("intIndexClass 222");
    indexClass stringIndexClass = new indexClass();
    stringIndexClass["string1"] = new thisClass("stringIndexClass string1");
    stringIndexClass["string2"] = new thisClass("stringIndexClass string2");
    Console.ReadLine();
  }
}
class indexClass
{
  /*声明属性*/
  private thisClass[] thisClassArr = new thisClass[10];
  private Hashtable thisClassStrArr = new Hashtable();
  /*创建索引器1 索引可以被重载,属于实例成员,不能声明为static*/
  public thisClass this[int index]
  {
    get { return thisClassArr[index]; }
    set { this.thisClassArr[index] = value; }
  }
  /*创建索引器2*/
  public thisClass this[string index]
  {
    get
    {
      return thisClassStrArr[index] as thisClass;
    }
    set { this.thisClassStrArr[index] = value; }
  }
}
class thisClass
{
  private string A { get; set; }
  public thisClass(string str)
  {
    /*当前类this 访问类中属性A 静态方法无法访问A属性*/
    this.A = str;
    Console.WriteLine(this.TestFun("TestFun :"));
  }
  private string TestFun(string args)
  {
    return args + this.A;
  }
}

运行结果如下图所示:

上一篇:MVC+EasyUI+三层新闻网站建立 详情页面制作方法(八)

栏    目:.NET代码

下一篇:深入分析C#连接Oracle数据库的连接字符串详解

本文标题:C#中this的使用实例分析

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

推荐教程

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

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

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

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

Copyright © 2020 代码驿站 版权所有