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