C#中this的作用:
1.代表当前实例
例:
public class Student
{
public int _age;
public Student(int age)
{
this._age = age; //代表当前实例
}
}
2.从构造函数中调用其他构造函数
例:
public class Student
{
public int _age;
public string _name;
public int _salary;
public Student(int age, string name, int salary)
{
this._age = age;
this._name = name;
this._salary = salary;
}
public Student(int age) : this(age, "NULL", 0) //调用上一个构造函数
{
}
}
3.作为当前实例用作参数
例:
public class Student
{
public int _age;
public Student(int age)
{
this._age = age;
}
public void show()
{
print(this); //作为参数
}
public void print(Student a)
{
Console.WriteLine(a._age);
}
}
4.this用作属性索引器,当类中有数组的字段时,可以通过this来创建字段的属性
例:
[修饰符] 数据类型 this[索引类型 index]
{
get{//获得属性的代码}
set{ //设置属性的代码}
}
class Practice
{
private int[] array = new int[100];
public int this[int para]
{
get { return array[para]; }
set { array[para] = value; }
}
}
static void Main()
{
var ceshi = new Practice();
ceshi[0] = 1;
Console.WriteLine(ceshi[0]);
Console.ReadKey();
}
C++中this的作用:
1.this是一个指针,只能在类中成员函数中使用,指向用来调用成员函数的对象。类中成员函数的第一个参数默认是T * const register this。
例:
class A
{
public:
int a;
void show()
{
a = 1;
this->a = 1;
//这两个一样
}
};