关键字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被定义为一个常量,因此,虽然在类的实例构造函数和实例函数成员中,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)。
this 是当前类 可以 this.当前类下的成员this.Page 当页类下的Page 属性
this包含自定义成员 this.Page不包含
public partical class aspx:Page { } this=aspx this.Page=base.Page
如果是 一个继承了System.Web.UI.Page 的类的话,是一样的
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被定义为一个常量,因此,虽然在类的实例构造函数和实例函数成员中,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)。
可以 this.当前类下的成员this.Page 当页类下的Page 属性
this.Page不包含
{
}
this=aspx
this.Page=base.Page
this.page 当前控件引用(所在)的页类
this.page代表page对象