virtual 与abstract在修饰方法上都是表示虚拟方法,但是在使用上存在区别 。 |
virtual:如果派生类中没有重写方法,那么在实例化派生类之后,按基类方法执行,如果基类已经重写了方法,则用派生类方法执行 。 abstract :基类必须为abstract类,方法并没有具体内容,只是在派生类中会对应方法内容。 |
举个例子,老师叫小明和小红去读课文,小红是个乖宝宝,就直接按老师的建议去做,但是小明想玩王者荣耀,所以就用override屏蔽了老师的话,具体程式如下,就可以用virtual了。 |
class Program
{
static void Main(string[] args)
{
xiaoming ccxiaoming = new xiaoming();
ccxiaoming.suggestion();
xiaohong ccxiaohong = new xiaohong();
ccxiaohong.suggestion();
Console.ReadLine();
}
}
class xiaoming : teacherCommand
{
public xiaoming():base()
{
}
public override void suggestion()
{
Console.WriteLine("play game");
}
}
class xiaohong : teacherCommand
{
public xiaohong()
: base()
{
}
}
class teacherCommand {
public virtual void suggestion() {
Console.WriteLine("read this article");
}
}
结果是:
play game
read this article
再举个例子,老师给小红和小明留了家庭作业要帮助家人做家务,但是并没有说要做什么,小明就帮妈妈打扫房间,而小红则是帮爷爷读报纸。
class Program
{
static void Main(string[] args)
{
xiaoming ccxiaoming = new xiaoming();
ccxiaoming.housework();
xiaohong ccxiaohong = new xiaohong();
ccxiaohong.housework();
Console.ReadLine();
}
}
class xiaoming : homework
{
public override void housework()
{
Console.WriteLine("help mother clean the room");
}
}
class xiaohong : homework
{
public override void housework()
{
Console.WriteLine("help grandpa read the newspaper ");
}
}
abstract class homework {
abstract void housework();
}
结果是:
help mother clean the room
help grandpa read the newspaper