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

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

Late Binding (การผูกพันล่าช้า) ใน C#

Late Binding = Dynamic Polymorphism = การตัดสินใจเรียกเมธอดใดในขณะ Run-time (ไม่ใช่ Compile-time) ทำผ่าน Virtual Methods และ Abstract Classes

Static vs Dynamic Polymorphism

ประเภทชื่ออื่นเวลาผูกพันกลไก
Static PolymorphismEarly BindingCompile-timeMethod Overloading, Operator Overloading
Dynamic PolymorphismLate BindingRun-timeVirtual/Override, Abstract Methods

ตัวอย่าง Late Binding (Virtual/Override)


using System;

namespace PolymorphismApplication
{
    // Base Class
    class Shape
    {
        protected int Width, Height;
        public Shape(int a = 0, int b = 0) { Width = a; Height = b; }
        
        // Virtual Method - อนุญาตให้ Override
        public virtual int Area()
        {
            Console.WriteLine("Parent class area:");
            return 0;
        }
    }
    
    // Derived Classes
    class Rectangle : Shape
    {
        public Rectangle(int a = 0, int b = 0) : base(a, b) {}
        public override int Area()
        {
            Console.WriteLine("Rectangle class area:");
            return Width * Height;
        }
    }
    
    class Triangle : Shape
    {
        public Triangle(int a = 0, int b = 0) : base(a, b) {}
        public override int Area()
        {
            Console.WriteLine("Triangle class area:");
            return Width * Height / 2;
        }
    }
    
    // Caller ใช้ Base Class Reference
    class Caller
    {
        public void CallArea(Shape shape)
        {
            int area = shape.Area(); // Late Binding: เรียก Override Method จริง
            Console.WriteLine($"Area: {area}");
        }
    }
    
    class Tester
    {
        static void Main(string[] args)
        {
            Caller c = new Caller();
            Rectangle r = new Rectangle(10, 7);
            Triangle t = new Triangle(10, 5);
            
            c.CallArea(r); // Late Binding -> Rectangle.Area()
            c.CallArea(t); // Late Binding -> Triangle.Area()
            Console.ReadKey();
        }
    }
}

ผลลัพธ์


Rectangle class area:
Area: 70
Triangle class area:
Area: 25

Late Binding อื่นๆ ใน C#

  • Reflection: type.GetMethod("Name").Invoke(obj, args)
  • dynamic Keyword (C# 4.0+): dynamic obj = GetObject(); obj.SomeMethod(); (DLR)
  • Delegates/Func/Action: ผูกพันเมธอดใน Runtime

ข้อดี/ข้อเสีย

ข้อดีข้อเสีย
Extensible (เพิ่ม Subclass ได้โดยไม่แก้ Base)ช้ากว่า Early Binding (Virtual Dispatch)
Polymorphic BehaviorCompile-time Safety น้อยกว่า
Plugin ArchitectureDebugging ยากกว่า