您的位置:首页 > 其它

继承中的构造函数的问题-base,this的用法

2012-08-18 23:27 549 查看
先写一个父类:

class Person
{

public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}


在写一个继承这个父类的子类

class Student : Person
{
public Student(string name, int age, double score)
{
this.Name = name;
this.Age = age;
this.Score = score;
}
public double Score
{
get;
set;
}
}


实例化子类并调用:

Student stu = new Student("张三", 18, 100);


编译运行成功!证明我们的写法是没有问题的!
这个时候我们修改下父类的代码:

class Person
{

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

public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}


这个时候编译就会出错:提示缺少一个无参数的构造函数:
少什么我们就先加什么:那么我们就给父类增加一个无参数的构造函数

class Person
{

public Person()
{
Console.WriteLine("Person类中的无参数的构造函数。。。。");
}

public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}


我们在编译,提示编译成功!

证明在调用子类的构造函数会默认去调用父类中的无参数的构造函数!继承的时候,构造函数不能被继承

但是当父类中不存在无参数的构造函数呢!

class Person
{

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

public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}


这个时候我们就可以使用base方法,在子类中制定要调用父类的构造函数,这样子类就不会默认的去调用父类中无参数的构造函数,编译也不会报错

class Student : Person
{

//不修改父类,而是在子类的构造函数后面通过: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;
}
}


上面讲了Base的用法,下面我们将下this的用法!

先看一段代码

public class Person : MyClass
{
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 = name;
}
public Person(string name, int age)

{
this.Name = name;
this.Age = age;
}
public Person(string name, string email)

{
this.Name = name;
this.Email = email;
}

public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
public string Email
{
get;
set;
}

public double Salary
{
get;
set;
}
}


通过上面的代码你是不是发现一些问题:有很多重复的地方,一个类里面有很多种构造方法,如果每一个我们都给里面的参数赋值的话,显得非常的麻烦,通过this我们就能更好的优化这些代码,并且清晰明了

public class Person : MyClass
{
public Person(string name, int age, string email, double salary)
{
this.Name = name;
this.Age = age;
this.Email = email;
this.Salary = salary;
}

//this作用1:在当前类的构造函数后面通过:this来调用当前类自己的其他构造函数。
public Person(string name)
: this(name, 0, null, 0)
{
// this.Name = name;
}
public Person(string name, int age)
: this(name, age, null, 0)
{
//this.Name = name;
//this.Age = age;
}
public Person(string name, string email)
: this(name, 0, email, 0)
{
//this.Name = name;
//this.Email = email;
}

public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
public string Email
{
get;
set;
}

public double Salary
{
get;
set;
}
}


当然this还有很多其它的用法,不仅仅是这一种 ,不同的场合有不同的含义!本文仅介绍在构造函数中的用法!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: