本篇文章主要介绍了详解C#用new和override来实现抽象类的重写区别,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧。
正文
详解C#用new和override来实现抽象类的重写区别
一,抽象的实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
using system; using system.collections.generic; using system.linq; using system.text; namespace virtualdemo { class program { static void main( string [] args) { //bclass a = new bclass(); 抽象类无法被实例 class1 c = new class1(); bclass c2 = c; c2.methoda(); c.methoda(); c2.methodb(); c.methodb(); c2.methodc(); c.methodc(); console.readkey(); } } abstract class bclass //抽象类无法被实例 { public virtual void methoda() { console.writeline( "bclassa" ); } public virtual void methodb() { console.writeline( "bclassb" ); } public virtual void methodc() { console.writeline( "bclassc" ); } } class class1 : bclass { public void methoda() { console.writeline( "methoda" ); } //如果一个虚函数 在子类中没有通过override关键字,那么这个方法就没有被重写,而是被隐藏了 public override void methodb() { console.writeline( "methodb" ); } public override void methodc() { base .methodc(); } } } |
从上图得出的结果是:
综上:抽象类的虚方法需要被重写,那问题来了重写有两种方式,new和override又有什么区别
二,new和override重写的区别:
发表评论