如果定义的类中有一个成员变量为a,在类的成员函数中又定义了一个局部变量a,此时就必须使用this关键字来指示类的成员,
也就是类的成员变量a写为this.a 。写的那些响应函数,其实都是类方法。
在程序运行后,方法可能会被很多这个类的实例(对象)来调用。
那么请问,系统怎么知道调用这个类方法的是谁?是哪个对象? 所以,这时this就发挥它的作用了
每当一个对象调用这个类方法的时候,系统就会自动把这个对象的指针赋给this指针 this指当前类
比如在一个AAA类里有一个aaa的方法
在这个AAA类中调用这个aaa方法就可以用this.aaa 如果是在别的类中就要实例化一个对象来调用这个方法
AAA a=new AAA();
a.aaa;
在静态的方法中不能使用 this
如 main 方法就是一个静态方法
this 是保留的指针指向当前对象,它的好处就是在编译期就可以获得对象的地址。比如一个类中有个成员类,成员类需使用上层类的函数,就可以把 this 传到成员类中 this 关键字引用类的当前实例
以下是调用本内中的构造函数,用 this
using System;
namespace CallConstructor
{
public class Car
{
int petalCount = 0;
String s = "null";
Car(int petals)
{
petalCount = petals;
Console.WriteLine("Constructor w/int arg only,petalCount = " + petalCount);
}
Car(String s, int petals) : this(petals) //第一个this的意思是调用Car(int petals)方法的属性petals
{
//第二个this的意思是实例化Car(String s, int petals)方法中的参数s(this.s = s)
this.s = s;
Console.WriteLine("String & int args");
}
Car() : this("hi", 47) //第三个this是调用Car(String s, int petals)方法的两个参数并传参
{
Console.WriteLine("default constructor");
}
public static void Main()
{
Car x = new Car();
Console.Read();
}
}
}
//结果:
//Constructor w/int arg only,petalCount = 47
//String & int args
//default constructor
this出现了,代表它所在的类的对象 c#中 this保留字的用法
this 关键字将引用类的当前实例静态成员函数没有 this 指针this 关键字可用于从构造函数实例方法和实例访问器中访问成员
以下是 this 的常用用途:
限定被相似的名称隐藏的成员,
例如:
public Employee(string name, string alias)
{
this.name = name;
this.alias = alias;
}
将对象作为参数传递到其他方法,
例如:
CalcTax(this);
声明索引器,
例如:
public Employee(string name, string alias)
{
this.name = name; this.alias = alias;
}
将对象作为参数传递到其他方法,例如:
CalcTax(this);
声明索引器,例如:
public int this [int param]
{
get
{
return array[param];
}
set
{
array[param] = value;
}
}
阅读(291) | 评论(0) | 转发(0) |