Polymorphism (พหุรูป) ความสามารถที่ Object แสดงพฤติกรรมต่างกันได้ ขึ้นอยู่กับ Type จริง แบ่ง 2 แบบ:
1. Static Polymorphism (Compile-time / Early Binding)
- Method Overloading - เมธอดชื่อเดียว พารามิเตอร์ต่างกัน
- Operator Overloading - นิยาม Operator ใหม่สำหรับ Type
- ตัดสินใจที่ Compile-time
2. Dynamic Polymorphism (Runtime / Late Binding)
- Method Overriding - Virtual/Override
- Abstract Classes/Methods
- Interface Implementation
- ตัดสินใจที่ Runtime
ตัวอย่าง Static Polymorphism (Method Overloading)
using System;
namespace PolymorphismApplication
{
class PrintData
{
public void Print(int i)
{
Console.WriteLine("Printing int: {0}", i);
}
public void Print(double f)
{
Console.WriteLine("Printing float: {0}", f);
}
public void Print(string s)
{
Console.WriteLine("Printing string: {0}", s);
}
}
class Program
{
static void Main(string[] args)
{
PrintData p = new PrintData();
p.Print(5); // int
p.Print(500.263); // double
p.Print("Hello C#"); // string
Console.ReadKey();
}
}
}
ผลลัพธ์
Printing int: 5 Printing float: 500.263 Printing string: Hello C#
สรุป
| ประเภท | กลไก | Binding Time | ตัวอย่าง |
|---|---|---|---|
| Static | Overloading | Compile-time | Print(int), Print(string) |
| Dynamic | Overriding | Runtime | Virtual Method, Abstract |