您的位置:首页 > 职场人生

黑马程序员--this与base总结

2013-04-20 23:01 197 查看
------- Windows Phone 7手机开发.Net培训、期待与您交流! -------

this:

1.
作为当前类的对象,调用类中的成员this.成员

MyCar c2 =
this.Car;
2. 调用本类中的其他构造函数
构造函数:this()

public class
Person
{
public Person(string name,
int age, string email,
double salary) //含有多个参数的构造函数
{
this.Name = name;
this.Age = age;
this.Email = email;
this.Salary = salary;
}

//定义另一个构造函数继承本类中参数最全的构造函数。
public Person(string name) //将有参的值传过来,没参的写默认值
:this(name,0,null,0) //通过this关键字调用当前类的其它构造函数
{
//this.Name = name;
//由于调用的构造函数中已经进行了赋值,所以无需再赋值
}

public Person(string name,
int age)
:this(name,age,null,0)
{
//this.Name = name;
//this.Age = age;
}
}

base:

1.
调用父类中的成员,base无法取得子类独有的成员。

//在一般情况下,如果子类继承了父类的成员,那么在子类中,通过this.成员或base.成员访问的都是一样的,除非父类中的成员子类继承后又重写了
MyCar c1 =
base.Car;
MyCar c2 =
this.Car;

2.在子类中调用父类的有参的构造函数。子类构造函数:base(参数)

类在继承的时候,构造函数不能被继承,子类的构造函数会默认去调用父类中的无参数的构造函数。此时如果子类和父类中都定义了有参数的构造函数,子类在调用父类时,将找不到父类中无参数的构造函数,程序将会报错。

修正此错误除了在父类中增加一个无参构造函数外,还可以使用另一个方法:在子类的构造函数后面加一个base(),使子类不再默认调用父类无参的构造函数,而是调用父类中有参数的构造函数。

不修改父类,而是在子类的构造函数后面通过:base(),显示的去调用父类的某个有参构造函数。

//父类中的构造函数
public Person(string name,
int age)
{
this.Name = name;
this.Age = age;
Console.WriteLine("Person类中的有参数的构造函数");
}
//子类中的构造函数

public Student(string name,
int age, double score)
:base(name,age) //通过base调用父类中带两个参数的构造函数
{
//this.Name = name;
//由于继承了父类的有参构造函数,在父类中已经初始化,所以子类中不用再初始化
//this.Age = age;
this.Score = score;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: