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

ความแตกต่างระหว่าง Delegates และ Events ใน C#


เปรียบเทียบ Delegates และ Events ใน C#

Delegate

  • ประกาศด้วย Keyword delegate
  • เป็น Function Pointer
  • เก็บ Reference ของ Methods หนึ่งหรือหลายตัวใน Runtime
  • เป็น Keyword อิสระ ไม่พึ่ง Events
  • มีเมธอด Combine() และ Remove() จัดการ Invocation List
  • ส่งเป็น Parameter ให้ Method ได้
  • Operator = กำหนด Method เดี่ยว, += เพิ่มหลาย Method

Event

  • ประกาศด้วย Keyword event
  • เป็น Notification Mechanism ที่พึ่งพา Delegate
  • ขึ้นอยู่กับ Delegate (ไม่สามารถสร้าง Event ได้โดยไม่มี Delegate)
  • เป็น Wrapper รอบ Delegate Instance
  • ป้องกัน User ของ Delegate จากการ Reset Delegate และ Invocation List
  • อนุญาต Add/Remove Targets จาก Invocation List เท่านั้น
  • Class EventInfo ตรวจสอบ Events และ Bind Event Handlers
  • มีเมธอด AddEventHandler() และ RemoveEventHandler()
  • Event สามารถ Raise ได้ แต่ไม่สามารถส่งเป็น Parameter ให้ Method ได้
  • Operator = ใช้กับ Event ไม่ได้
  • Operator += และ -= ใช้ Add/Remove Event Handlers (เรียก AddEventHandler/RemoveEventHandler ภายใน)