------- Windows Phone 7手机开发、.Net培训、期待与您交流! -------
this和base有时候容易混淆,在这里总结一下。
this:1.作为当前类的对象,可以调用类中的成员。this.成员(调用成员,自己)
2.调用本类的其他构造函数。:this()(调用构造函数,自己)
base:
1.调用父类中的成员(调用成员,父类)base点不出子类独有成员。
2.调用父类中的构造函数(调用构造函数,父类)
当调用从父类中继承过来的成员的时候,如果子类没有重写则this.成员;与base.成员;没有区别。如果子类重写了父类成员,则this.成员;调用的是子类重写以后的。base.成员;调用的依然是父类的成员。
子类构造函数必须指明调用父类哪个构造函数
例子1: base使用方法
class Person
{
////在父类中增加一个无参数的构造函数。
////这时子类的构造函数就可以找到父类中的无参构造函数了。
public Person()
{
Console.WriteLine("Person类中的无参数的构造函数。。。。");
}
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
public Person(string name)
{
this.Name = name;
this.Age = 0;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
//1.继承的时候,构造函数不能被继承。
//2.字类的构造函数会默认去调用父类中的无参数的构造函数
class Student : Person
{
//修正错误方法2:不修改父类,而是在子类的构造函数后面通过:base(),显示的去调用父类的某个构造函数。
public Student(string name, int age, double score)
: base(name, age) //base的作用1:在子类中调用父类的构造函数。
{
// this.Name = name;
//this.Age = age;
this.Score = score;
}
public double Score
{
get;
set;
}
}
class Teacher : Person //继承自Person类
{
public Teacher(string name, int age, double salary)
: base(name)//初始化Person的构造函数
{
//this.Name = name;
this.Age = age;
this.Salary = salary;
}
public double Salary
{
get;
set;
}
}
例子2:this的学习方法。
public class MyCar
{
}
public class Person
{
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
public string Email
{
get;
set;
}
public MyCar Car
{
get;
set;
}
}
public class Student : Person //Studeng继承自Person
{
public double Score
{
get;
set;
}
public void Test()
{
// Console.WriteLine(this.Name);
Console.WriteLine(base.Name);
//string s1 = this.Name;
//在一般情况下,如果子类继承了父类的成员
//那么在子类中,通过this.成员或base.成员都是访问的是一样的。
//除非父类中的成员子类继承后又重写了。
MyCar c1 = base.Car;
MyCar c2 = this.Car;
}
}
------- Windows Phone 7手机开发 、 .Net培训 、期待与您交流! -------