Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Early Binding ใน C# คืออะไร

Early Binding (Static Binding) คือการผูก Method กับ Object ที่ **Compile-time** - Compiler รู้ว่าเรียก Method ไหนจาก Method Signature

กลไก 2 แบบของ Static Polymorphism

  1. Function Overloading - เมธอดชื่อเดียว พารามิเตอร์ต่างกัน
  2. 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 TimeCompile-timeRuntime
MechanismOverloadingOverriding (Virtual/Abstract)
Performanceเร็วกว่าช้ากว่า (v-table lookup)
Flexibilityน้อยกว่ามากกว่า (Polymorphism)
Type Safetyสูง (Compile-time Check)ต่ำกว่า (Runtime Check)