本篇文章主要介绍了详解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)
{
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" ); }
public override void MethodB() { Console.WriteLine( "MethodB" ); }
public override void MethodC() { base.MethodC(); }
}
}
|
Salin selepas log masuk
从上图得出的结果是:

综上:抽象类的虚方法需要被重写,那问题来了重写有两种方式,new和override又有什么区别
二,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 36 37 38 39 40 41 42 43 44 45 46 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Virtualdemo
{
class Program
{
static void Main(string[] args)
{
Teacher t = new Teacher();
Student stu = t;
stu.Exam();
stu.Say();
t.Say();
Console.ReadKey();
}
}
public abstract class Student
{
public virtual void Exam()
{
Console.WriteLine( "学生都要考试" );
}
public void Say()
{
Console.WriteLine( "我是学生" );
}
}
public class Teacher : Student
{
public override void Exam()
{
Console.WriteLine( "老师不用考试" );
}
public new void Say()
{
Console.WriteLine( "我是老师" );
}
}
}
|
Salin selepas log masuk
结果显示为:

综上总结:
1、如果基类没有定义虚方法,那子类只能使用new,而不能使用override
2、基类有没有定义虚方法,子类都可以使用new
3、子类使用new并不叫重写,而是子类新创建一个方法,只是新创建的这个方法刚好跟基类中的方法同名
以上就是详解C#用new和override来实现抽象类的重写区别的内容,更多相关内容请关注PHP中文网(www.php.cn)!