C# 多型
多型和重寫方法
多型性意為“多種形式”,它發生在我們有許多透過繼承相互關聯的類時。
正如我們在上一章中指定的; 繼承 允許我們從另一個類繼承欄位和方法。多型使用這些方法來執行不同的任務。這使我們能夠以不同的方式執行單個操作。
例如,考慮一個名為 Animal
的基類,它有一個名為 animalSound()
的方法。動物的派生類可以是豬、貓、狗、鳥 - 它們也有自己對動物聲音的實現(豬會發出哼哼聲,貓會發出喵喵聲等)。
示例
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Pig : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
class Dog : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
還記得我們在 繼承章節 中使用 :
符號從類繼承嗎?
現在我們可以建立 Pig
和 Dog
物件,並在兩者上呼叫 animalSound()
方法。
示例
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Pig : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
class Dog : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
輸出將是:
動物發出聲音
動物發出聲音
動物發出聲音
不是我期望的輸出
上面示例的輸出可能不是您期望的。那是因為當基類方法和派生類方法共享相同名稱時,基類方法會覆蓋派生類方法。
但是,C# 提供了一個選項來重寫基類方法,方法是在基類中的方法中新增 virtual
關鍵字,並在每個派生類方法中使用 override
關鍵字。
示例
class Animal // Base class (parent)
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Pig : Animal // Derived class (child)
{
public override void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
class Dog : Animal // Derived class (child)
{
public override void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
輸出將是:
動物發出聲音
豬說:哼哼
狗說:汪汪
為什麼要使用“繼承”和“多型性”?以及何時使用?
- 它有利於程式碼重用:在建立新類時重用現有類的欄位和方法。