c#中this的用法
比如你的类中有一个成员变量为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();
}
}
}