Early Binding (Static Binding) คือการผูก Method กับ Object ที่ **Compile-time** - Compiler รู้ว่าเรียก Method ไหนจาก Method Signature
กลไก 2 แบบของ Static Polymorphism
- Function Overloading - เมธอดชื่อเดียว พารามิเตอร์ต่างกัน
- Operator Overloading - นิยาม Operator ใหม่สำหรับ Type
ตัวอย่าง Function 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); // เรียก Print(int) - Compile-time
p.Print(500.263); // เรียก Print(double) - Compile-time
p.Print("Hello C#"); // เรียก Print(string) - Compile-time
Console.ReadKey();
}
}
}
ผลลัพธ์
Printing int: 5 Printing float: 500.263 Printing string: Hello C#
Operator Overloading ตัวอย่าง
public struct Complex
{
public double Real, Imag;
public static Complex operator +(Complex a, Complex b)
{
return new Complex { Real = a.Real + b.Real, Imag = a.Imag + b.Imag };
}
}
// ใช้งาน
Complex c1 = new Complex { Real = 1, Imag = 2 };
Complex c2 = new Complex { Real = 3, Imag = 4 };
Complex c3 = c1 + c2; // ใช้ Operator + ที่ Overload
Early vs Late Binding
| คุณสมบัติ | Early Binding (Static) | Late Binding (Dynamic) |
|---|---|---|
| Binding Time | Compile-time | Runtime |
| Mechanism | Overloading | Overriding (Virtual/Abstract) |
| Performance | เร็วกว่า | ช้ากว่า (v-table lookup) |
| Flexibility | น้อยกว่า | มากกว่า (Polymorphism) |
| Type Safety | สูง (Compile-time Check) | ต่ำกว่า (Runtime Check) |