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

Events vs Delegates ใน C#: ความแตกต่างและการใช้งาน

Delegate คือ ตัวแปรอ้างอิง (Reference Type) ที่เก็บการอ้างอิงไปยังเมธอด สามารถเปลี่ยนเมธอดที่ชี้ไปได้ใน Runtime

Event คือ Wrapper รอบ Delegate ที่จำกัดการเข้าถึง - ป้องกันไม่ให้โค้ดภายนอก Invoke หรือ Clear Delegate โดยตรง ลดความเสี่ยงของข้อผิดพลาด

Delegate

// ประกาศ Delegate
public delegate void DemoDelegate(string message);

// ใช้งาน
DemoDelegate d = MethodA;
d += MethodB; // Multicast
d("Hello");   // เรียก MethodA และ MethodB

Event

// ประกาศ Event (ต้องมี Delegate ก่อน)
public delegate void DemoDelegate(string message);
public event DemoDelegate TestEvent;

// ใช้งาน (ภายในคลาสเดียวกัน)
TestEvent += DemoData;  // Subscribe
TestEvent -= DemoData;  // Unsubscribe
TestEvent?.Invoke("Data"); // Raise (ปลอดภัยกับ null)

ความแตกต่างสำคัญ

คุณสมบัติDelegateEvent
การ Invokeได้จากที่ไหนก็ได้ได้เฉพาะในคลาสที่ประกาศ
การ Assign (=)ได้ไม่ได้ (ใช้ += -= เท่านั้น)
การ Clear (null)ได้ไม่ได้
วัตถุประสงค์Callback, Strategy PatternNotification, Observer Pattern

ตัวอย่างรวม

public delegate void Notify(string message);

public class Publisher
{
    // Event wrapper
    public event Notify OnNotify;
    
    public void DoSomething()
    {
        OnNotify?.Invoke("Something happened");
    }
}

public class Subscriber
{
    public void Subscribe(Publisher p)
    {
        p.OnNotify += HandleNotify;
    }
    
    private void HandleNotify(string msg)
    {
        Console.WriteLine($"Received: {msg}");
    }
}

สรุป: ใช้ Event สำหรับการแจ้งเตือน (Notification) ใช้ Delegate สำหรับ Callback/Strategy โดยตรง