Compile-time Polymorphism (Static Polymorphism) ใน C#
Static Polymorphism = การตัดสินใจเรียกเมธอดใดในขณะ Compile-time (Early Binding) ทำได้ 2 วิธี: Method Overloading และ Operator Overloading
1. Method Overloading (Function Overloading)
หลายเมธอดชื่อเดียวกัน Signature ต่างกัน (พารามิเตอร์ต่างชนิด/จำนวน)
ตัวอย่าง
using System;
namespace PolymorphismApplication
{
class PrintData
{
public void Print(int i)
{
Console.WriteLine($"Printing int: {i}");
}
public void Print(double f)
{
Console.WriteLine($"Printing float: {f}");
}
public void Print(string s)
{
Console.WriteLine($"Printing string: {s}");
}
}
class Tester
{
static void Main(string[] args)
{
PrintData p = new PrintData();
p.Print(5); // เรียก Print(int)
p.Print(500.263); // เรียก Print(double)
p.Print("Hello C#"); // เรียก Print(string)
Console.ReadKey();
}
}
}
ผลลัพธ์
Printing int: 5
Printing float: 500.263
Printing string: Hello C#
2. Operator Overloading
กำหนดพฤติกรรมของ Operator (+, -, ==, !=, etc.) สำหรับ Custom Types
ตัวอย่าง: Complex Number
public struct Complex
{
public double Real, Imag;
public Complex(double real, double imag) { Real = real; Imag = imag; }
// Overload + Operator
public static Complex operator +(Complex a, Complex b)
{
return new Complex(a.Real + b.Real, a.Imag + b.Imag);
}
// Overload == และ != ต้องคู่กัน
public static bool operator ==(Complex a, Complex b)
=> a.Real == b.Real && a.Imag == b.Imag;
public static bool operator !=(Complex a, Complex b)
=> !(a == b);
public override string ToString() => $"{Real} + {Imag}i";
}
// ใช้งาน
var c1 = new Complex(1, 2);
var c2 = new Complex(3, 4);
var sum = c1 + c2; // (4 + 6i)
Console.WriteLine(sum);
Static vs Dynamic Polymorphism
| ลักษณะ | Static (Compile-time) | Dynamic (Run-time) |
|---|---|---|
| Binding Time | Compile-time | Run-time |
| กลไก | Overloading, Operators | Virtual/Override, Abstract |
| Performance | เร็วกว่า (Direct Call) | ช้ากว่า (V-Table Lookup) |
| Flexibility | น้อยกว่า | มากกว่า (Extensible) |
เมื่อไหร่ใช้แบบไหน
- Static: พฤติกรรมคงที่ รู้จัก Type ตอน Compile (Math Operations, Utilities)
- Dynamic: พฤติกรรมเปลี่ยนตาม Runtime Type (Plugin, Framework, Extensibility)