本文实例讲述了C#中实现子类调用父类的方法,分享给大家供大家参考之用。具体方法如下:
一、通过子类无参构造函数创建子类实例
创建父类Person和子类Student。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public
class
Person
{
public
Person()
{
Console.WriteLine(
"我是人"
);
}
}
public
class
Student : Person
{
public
Student()
{
Console.WriteLine(
"我是学生"
);
}
}
|
在客户端通过子类无参构造函数创建子类实例。
|
1
2
3
4
5
6
7
8
|
class
Program
{
static
void
Main(
string
[] args)
{
Student student =
new
Student();
Console.ReadKey();
}
}
|
输出结果:
|
1
2
|
我是人
我是学生
|
可见:通过调用子类无参构造函数创建子类实例,会默认调用父类无参构造函数。
如果把父类的无参构造函数去掉,会怎样呢?
--结果会报"Person不包含0个参数的构造函数"错。
二、通过子类有参构造函数创建子类实例
再同时为子类和父类添加有参构造函数。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public
class
Person
{
public
Person()
{
Console.WriteLine(
"我是人"
);
}
public
Person(
string
name)
{
Console.WriteLine(
"我是人,我的名字叫{0}"
, name);
}
}
public
class
Student : Person
{
public
Student()
{
Console.WriteLine(
"我是学生"
);
}
public
Student(
string
name)
{
Console.WriteLine(
"我是学生,我的名字叫{0}"
, name);
}
}
|
在客户端通过子类有参构造函数创建子类实例。
|
1
2
|
Student student =
new
Student(
"小明"
);
Console.ReadKey();
|
输出结果:
|
1
2
|
我是人
我是学生,我的名字叫小明
|
可见:通过调用子类有参构造函数,同样默认会调用父类无参构造函数。
三、在子类中明确指出调用哪个父类构造函数
以上,默认调用了父类的无参构造函数,但如何调用父类的有参构造函数呢?
--在子类中使用base
在子类Student中的有参构造函数中使用base,明确调用父类有参构造函数。
|
1
2
3
4
5
6
7
8
9
10
11
12
|
public
class
Student : Person
{
public
Student()
{
Console.WriteLine(
"我是学生"
);
}
public
Student(
string
name)
:
base
(name)
{
Console.WriteLine(
"我是学生,我的名字叫{0}"
, name);
}
}
|
客户端
|
1
2
|
Student student =
new
Student(
"小明"
);
Console.ReadKey();
|
输出结果:
|
1
2
|
我是人,我的名字叫小明
我是学生,我的名字叫小明
|
四、通过子类设置父类的公共属性
在父类Person中增加一个Name公共属性,并在父类的构造函数中对Name属性赋值。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public
class
Person
{
public
string
Name {
get
;
set
; }
public
Person()
{
Console.WriteLine(
"我是人"
);
}
public
Person(
string
name)
{
this
.Name = name;
Console.WriteLine(
"我是人,我的名字叫{0}"
, name);
}
}
|
在客户端:
|
1
2
3
|
Student student =
new
Student(
"小明"
);
Console.WriteLine(
"子类获取父类的Name属性值为{0}"
, student.Name);
Console.ReadKey();
|
输出结果:
|
1
2
3
|
我是人,我的名字叫小明
我是学生,我的名字叫小明
子类获取父类的Name属性值为小明
|
以上代码的执行路径是:
→调用子类有参构造函数,并把该参数传值给父类有参构造函数
→调用父类有参构造函数,并给父类公共属性Name赋值
→子类实例调用父类的公共属性
其实,以上的做法在分层架构设计中已经得到了很好的使用。在分层架构中,通常会为所有的Repository创建一个基类,在基类中设计一个代表当前Repository的属性,并在基类的构造函数中为该属性赋值;最终,在创建子类Repository实例时,在为基类的、代表当前Repository的公共属性赋值。
在子类中,当父类通过base拿到子类的参数时,还可以对该参数做一些处理,比如代表父类的base把从子类拿到的参数转换成大写。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public
class
Student : Person
{
public
Student()
{
Console.WriteLine(
"我是学生"
);
}
public
Student(
string
name)
:
base
(ConvertToUpper(name))
{
Console.WriteLine(
"我是学生,我的名字叫{0}"
, name);
}
private
static
string
ConvertToUpper(
string
name)
{
return
name.ToUpper();
}
}
|
输出结果:
|
1
2
3
|
我是人,我的名字叫DARREN
我是学生,我的名字叫darren
子类获取父类的Name属性值为DARREN
|
总结:
①.通过子类无参构造函数创建子类实例,会默认调用父类的无参构造函数
②.通过子类有参构造函数创建子类实例,也会默认调用父类的无参构造函数
③.在子类构造函数中通过base关键字指明父类构造函数,当通过子类构造函数创建实例,会调用指明的、父类的构造函数
④.父类的公共属性可以通过子类来赋值,子类也可以获取到父类的公共属性
相信通过本文上述实例的分析,可以加深大家对C#类的初始化与继承的理解。希望本文所述对大家进一步的学习C#程序设计有所帮助。
