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

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

Static Binding (การผูกติดแบบคงที่) คือการเชื่อมโยงเมธอดกับอ็อบเจ็กต์ในขณะคอมไพล์ (Compile Time) เรียกอีกอย่างว่า Early Binding

C# รองรับ Static Polymorphism ผ่าน 2 เทคนิคหลัก:

1. Function Overloading (การโอเวอร์โหลดฟังก์ชัน)

อนุญาตให้มีหลายการนิยามสำหรับชื่อฟังก์ชันเดียวกันในขอบเขตเดียวกัน โดยแตกต่างกันที่พารามิเตอร์ (จำนวน ชนิด หรือลำดับ)

ตัวอย่าง Function Overloading

void Print(int i) {
    Console.WriteLine("Printing int: {0}", i);
}

void Print(double f) {
    Console.WriteLine("Printing float: {0}", f);
}

void Print(string s) {
    Console.WriteLine("Printing string: {0}", s);
}

2. Operator Overloading (การโอเวอร์โหลดออเปอเรเตอร์)

อนุญาตให้กำหนดพฤติกรรมของออเปอเรเตอร์สำหรับ User-defined Types โดยใช้คีย์เวิร์ด operator

ตัวอย่าง Operator Overloading

public class Box {
    public int Length { get; set; }
    public int Breadth { get; set; }
    public int Height { get; set; }
    
    // โอเวอร์โหลดออเปอเรเตอร์ +
    public static Box operator +(Box b, Box c) {
        Box box = new Box();
        box.Length = b.Length + c.Length;
        box.Breadth = b.Breadth + c.Breadth;
        box.Height = b.Height + c.Height;
        return box;
    }
}

คุณสมบัติของ Static Binding

  • เกิดขึ้นในขณะ Compile Time
  • ประสิทธิภาพสูง (ไม่มี Overhead ใน Runtime)
  • ใช้กับ Method Overloading และ Operator Overloading
  • ไม่สามารถเปลี่ยนพฤติกรรมได้ใน Runtime

Static Binding vs Dynamic Binding

คุณสมบัติ Static Binding Dynamic Binding
เวลาที่ผูกติด Compile Time Runtime
เทคนิค Overloading Overriding (Virtual/Override)
ประสิทธิภาพ สูงกว่า ต่ำกว่า (มี Overhead)
ความยืดหยุ่น ต่ำ สูง