this操作数代表的是指向此对象的参考指针。也就是说,在建立对象的实体后,我们就可以使用this来存取到此对象实体。另外,this操作数也可以用来解决名称相同的问题。 需要注意的是:静态方法中不能使用this。
base是在继承的时候调用父类成员(非私有成员)的时候用。
例如:
string _name;
protected double s;
public string Name
{
get { return _name; }
set { _name = value; }
}
int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
char _gender;
public char Gender
{
get { return _gender; }
set { _gender = value; }
}
public void PersonSay()
{
Console.WriteLine("我是Person{0}----{1}---{2}",this.Name,this.Age,this.Gender);
}
public Person(string name, int age, char gender)
{
this.Name = name;
this.Age = age;
this.Gender = gender;
}
而调用父类构造函数时需使用base
public class Student : Person
{
int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
public void StudentSay()
{
Console.WriteLine("我是学生");
}
public Student(string name, int age, char gender, int id)
: base(name, age, gender)
{
this.Id = id;
}
}
this还可以调用自己的构造函数
public Person(string name, int age, char gender, double chinese)
{
this.Name = name;
this.Age = age;
this.Gender = gender;
this.Chinese = chinese;
}
//this另一种作用调用自己的构造函数
public Person(string name, int age, char gender)
: this(name, age, gender, 0)
{
//this.Name = name;
//this.Age = age;
//this.Gender = gender;
}
public Person(string name, int age, double chinese)
: this(name, age, '\0', chinese)
{
//this.Name = name;
//this.Age = age;
//this.Chinese = chinese;
}
这样可以增强复用性。 |