舉例如下
public class Shape {
public virtual void Draw() {
System.Console.WriteLine("a shape is drawing ....");
}
}
class Circle : Shape {
public override void Draw() {
System.Console.WriteLine("a circle is drawing ....");
base.Draw();
}
}
class Rectangle : Shape {
public override void Draw() {
System.Console.WriteLine("a rectangle is drawing ....");
base.Draw();
}
}
class Triangle : Shape {
public override void Draw() {
System.Console.WriteLine("a triangle is drawing ....");
base.Draw();
}
}
class ShapeTest {
static void Main(string[] args) {
System.Collections.Generic.List<Shape> shapes = new System.Collections.Generic.List<Shape>();
shapes.Add(new Rectangle());
shapes.Add(new Triangle());
shapes.Add(new Circle());
foreach (Shape s in shapes) {
s.Draw();
}
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:polymorphism.cs
功能:示範 C# 程式
作者:張凱慶
時間:西元 2013 年 6 月 */Sharp 為 Rectangle 、 Triangle 、 Circle 的父類別,此例將 Sharp 當作三個子類別的通用類別
System.Collections.Generic.List<Shape> shapes = new System.Collections.Generic.List<Shape>();
shapes.Add(new Rectangle());
shapes.Add(new Triangle());
shapes.Add(new Circle());
foreach (Shape s in shapes) {
s.Draw();
}編譯執行,結果如下

| 中英文術語對照 | |
|---|---|
| 多型 | polymorphism |
| 繼承 | inheritance |
| 父類別 | superclass |
| 子類別 | subclass |
| 型態 | type |
您可以繼續參考
泛型
多型
迭代器
名稱空間
相關目錄
回 C# 快速導覽
回 C# 教材
回首頁
參考資料
Standard ECMA-334 C# Language Specification
msdn: 多型 (C# 程式設計手冊)
沒有留言:
張貼留言