如何理解C# 多态中的override和new
如何理解C#中的override和new,看了很多博客和文章,从中收获了不少关于继承和多态的知识。但是理解层面还不够深入,不入本质。
但是,对象以及继承和多态,往往都是和现实世界类比而成的。它们源于现实世界,而高于之。我们何尝不从现实世界入手,对其实现机制进行类比。用我们比较熟悉的方式去理解呢?
见如下代码:
[csharp]
01.namespace ClassLibrary1
02.{
03. public class Teacher
04. {
05. public virtual void Paper()
06. {
07. Console.Write("老师出试卷");
08. }
09. }
10. public class S1 : Teacher
11. {
12. public override void Paper()
13. {
14. Console.WriteLine("S1做试卷");
15. }
16. }
17. public class S2 : S1
18. {
19. public override void Paper()
20. {
21. Console.WriteLine("S2重写了S1的试卷");
22. }
23. }
24. public class S3 : S2
25. {
26. public new void Paper()
27. {
28. Console.WriteLine("S3并没有重写S2的试卷,而是自己重新new了试卷");
29. }
30. }
31.}
32.
33.namespace ConsoleApplication1
34.{
35. class Program
36. {
37. static void Main(string[] args)
38. {
39.
40. Teacher t = new Teacher();
41. t.Paper(); //老师出试卷
42. S1 s1 = new S1();
43. s1.Paper(); //S1做试卷
44. S2 s2 = new S2();
45. s2.Paper(); //S2重写了S1的试卷
46. S3 s3 = new S3();
47. s3.Paper(); //S3并没有重写S2的试卷,而是自己重新new了试卷
48.
49. t = s3;
50. t.Paper();//!!S2重写了S1的试卷
51.
52. t = s2;
53. t.Paper();//S2重写了S1的试卷
54.
55. t = s1;
56. t.Paper();//S1做试卷
57.
58.
59. }
60. }
61.}
namespace ClassLibrary1
{
public class Teacher
{
public virtual void Paper()
{
Console.Write("老师出试卷");
}
}
public class S1 : Teacher
{
public override void Paper()
{
Console.WriteLine("S1做试卷");
}
}
public class S2 : S1
{
public override void Paper()
{
Console.WriteLine("S2重写了S1的试卷");
}
}
public class S3 : S2
{
public new void Paper()
{
Console.WriteLine("S3并没有重写S2的试卷,而是自己重新new了试卷");
}
}
}
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Teacher t = new Teacher();
t.Paper(); //老师出试卷
S1 s1 = new S1();
s1.Paper(); //S1做试卷
S2 s2 = new S2();
s2.Paper(); //S2重写了S1的试卷
S3 s3 = new S3();
s3.Paper(); //S3并没有重写S2的试卷,而是自己重新new了试卷
t = s3;
t.Paper();//!!S2重写了S1的试卷
t = s2;
t.Paper();//S2重写了S1的试卷
t = s1;
t.Paper();//S1做试卷
}
}
}
分析:为什么t=s3,t.Paper()显示结果是S2重写了S1的试卷呢?因为这个引用t是Teacher类的,所以先从Teacher类找到Paper()这个方法,然后发现被重写,所以又找到S1的Paper(),然后发现其又被重写,所以,继续往
补充:软件开发 , C# ,