当前位置: 移动技术网 > IT编程>开发语言>c# > C#中this的使用实例分析

C#中this的使用实例分析

2019年07月18日  | 移动技术网IT编程  | 我要评论
this关键字在c#程序设计中的应用非常频繁,今天本文就this关键字的用法做一番分析,希望能提对大家的c#程序设计有一定的帮助作用。具体分析如下: 1.代表当前类,在当

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;
  }
}

运行结果如下图所示:

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网