[英]Polymorphism without implementing all virtual methods
使用多態性時,不在所有派生類中實現虛擬方法被認為是一種糟糕的編程習慣嗎?
假設我有一個 Enemy class 和幾個派生類。 所有類型的敵人都有一個 Attack() 方法,但只有一部分能夠跳躍。 在這種情況下,除了獸人以外的所有敵人都有跳躍技能。
using System;
namespace Polymorphism
{
class Program
{
static void Main()
{
Enemy enemy1 = new Spider();
Enemy enemy2 = new Goblin();
Enemy enemy3 = new Orc();
}
}
abstract class Enemy
{
//I'm making this abstract because all derived classes will implement this anyway
public abstract void Attack();
//This is virtual because not all derived enemy types can jump
public virtual void Jump()
{
//nothing here
}
}
class Spider : Enemy
{
public override void Attack()
{
Console.WriteLine("Bite attack!");
}
public override void Jump()
{
Console.WriteLine("Spider jump animation");
}
}
class Goblin : Enemy
{
public override void Attack()
{
Console.WriteLine("Arrow attack!");
}
public override void Jump()
{
Console.WriteLine("Goblin jump animation");
}
}
class Orc : Enemy
{
public override void Attack()
{
Console.WriteLine("Axe attack!");
}
//no jump method here!
}
}
即使 orcs 不能跳躍,基類的 Jump() 方法仍然可以調用,即使它在 orcs 的情況下完全沒有做任何事情。 我發現 Intellisense 仍然“推薦”跳轉按鈕有點誤導,而且對我來說這也不是一個好的編程習慣。 這是一個糟糕的方法嗎?如果我真的希望能夠將我所有的敵人對象放在同一個數組中,有什么替代方法? 據我所知,您不能真正訪問派生類中的非重寫方法,並且轉換聽起來很麻煩。
您可以訪問 base class 中除 private 之外的任何方法。 嘗試這個
abstract class BaseEnemy
{
//I'm making this abstract because all derived classes will implement this anyway
public abstract void Attack();
}
abstract class AdvancedEnemy:BaseEnemy
{
//This is virtual because not all derived enemy types can jump
public virtual void Jump()
{
}
}
class Spider : AdvancedEnemy
{
public override void Attack()
{
Console.WriteLine("Bite attack!");
}
public override void Jump()
{
Console.WriteLine("Spider jump animation");
}
}
class Goblin : AdvancedEnemy
{
public override void Attack()
{
Console.WriteLine("Arrow attack!");
}
public override void Jump()
{
Console.WriteLine("Goblin jump animation");
}
}
class Orc : BaseEnemy
{
public override void Attack()
{
Console.WriteLine("Axe attack!");
}
//no jump method here!
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.