C#中this关键字-调用本类成员

关键字this有两种基本的用法,一是用来进行this访问,二是在声明构造函数时指定需要先执行的构造函数。

一、this访问

在类的实例构造函数和实例函数成员中,关键字this表示当前的类实例或者对象的引用。this不能用在静态构造函数和静态函数成员中,也不能在其他地方使用。

当在实例构造函数或方法内使用了与字段名相同的变量名或参数名时,可以使用this来区别字段和变量或者参数。下面的代码演示了this的用法。

public class Dog

{

public string name;

public int age;

public Dog()

{

}

public Dog(string name) // 在这个函数内,name是指传入的参数name

{

this.name = name; // this.name表示字段name

}

public Dog(string name, int age) // 在这个函数内,name是指传入的参数name

{ // age是指传入的参数age

this.name = name; // this.name表示字段name

this.age = age; // this.age表示字段age

// 非静态成员可以在构造函数或非静态方法中使用this.来调用或访问,也可以直接打变量的名字。因此这一句等效于name = name;

//但是这时你会发现的变量name与传入的参数name同名,这里会造成二定义,所以要加个this.表示等号左边的name是当前类自己的变量。

}

}

实际上,this被定义为一个常量,因此,虽然在类的实例构造函数和实例函数成员中,this可以用于引用该函数成员调用所涉及的实例,但是不能对this本身赋值或者改变this的值。比如,this++,--this之类的操作都是非法的。

二、this用于构造函数声明

可以使用如下的形式来声明实例构造函数:

<访问修饰符> 类名 (形式参数表) : this(实际参数表)

{

//语句块

}

其中的this表示该类本身所声明的、形式参数表与『实际参数表』最匹配的另一个实例构造函数,这个构造函数会在执行正在声明的构造函数之前执行。

比如:

// ThisAndConstructor.cs

// 关键字this用于声明构造函数

using System;

class A

{

public A(int n)

{

Console.WriteLine("A.A(int n)");

}

public A(string s, int n) : this(0)

{

Console.WriteLine("A.A(string s, int n)");

}

}

class Test

{

static void Main()

{

A a = new A("A Class", 1);

}

}

将输出:

A.A(int n)

A.A(string s, int n)

这说明,执行构造函数A(string s, int n)之前先执行了构造函数A(int n)。