Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Sự khác biệt giữa Delegate và Event trong C#

So sánh Delegate và Event trong C#.

Delegate

  • Khai báo bằng từ khóa delegate.
  • Là con trỏ hàm (function pointer).
  • Giữ tham chiếu đến 1 hoặc nhiều method tại runtime.
  • Từ khóa độc lập.
  • Không phụ thuộc vào event.
  • Có method Combine() và Remove() thêm/xóa method khỏi invocation list.
  • Có thể truyền làm tham số cho method.
  • Toán tử = gán 1 method đơn lẻ.
  • Toán tử += gán nhiều method (multicast).

Event

  • Khai báo bằng từ khóa event.
  • Là cơ chế thông báo (notification mechanism) phụ thuộc vào delegate.
  • Phụ thuộc delegate, không thể tạo event không có delegate.
  • Hiểu như wrapper bao quanh delegate instance.
  • Ngăn chặn user của delegate reset delegate và invocation list.
  • Chỉ cho phép add/remove target từ invocation list.
  • Class EventInfo kiểm tra event, bind event handler.
  • Method AddEventHandler(), RemoveEventHandler() thêm/xóa handler.
  • Event có thể raise (kích hoạt) nhưng không thể truyền làm tham số cho method.
  • Toán tử = KHÔNG dùng với event.
  • Toán tử += và -= add/remove event handler (gọi nội bộ AddEventHandler/RemoveEventHandler).

Tóm lại: Delegate là kiểu dữ liệu function pointer; Event là wrapper an toàn xung quanh delegate, chỉ expose add/remove handler, dùng cho pattern publisher-subscriber.