Difference between delegates and events in C#

WBOY
Release: 2023-08-30 12:25:13
forward
875 people have browsed it

C# 中的委托和事件之间的区别

In this article, we will understand the difference between delegates and events in C#.

Delegate

  • It can be declared using the "delegate" keyword.
  • It is a function pointer.

  • It holds a reference to one or more methods at runtime.

  • It is an independent keyword.

  • It does not depend on events.

  • It contains Combine() and Remove() methods which helps in adding methods to the call list middle.

  • It can be passed as a parameter to a method.

  • The "=" operator can be used to assign a single method.

  • The "=" operator can be used to assign multiple methods to a delegate.

Events

  • can be declared using the "event" keyword.

  • It can be defined as a notification mechanism that relies on delegation.

  • It depends on the commission.

  • It cannot be created without a delegate.

  • It can be understood as a wrapper for delegate instances.

  • This helps prevent users of the delegate from resetting the delegate and its call list.

  • It only allows adding or removing targets from the call list.

  • The "EventInfo" class checks for events and helps bind event handlers.

  • These handlers include methods such as AddEventHandler() and RemoveEventHandler(), which help add and remove methods to the call list respectively.

  • Events can be raised but cannot be passed as parameters to methods.

  • The "=" operator cannot be used with events.

  • The "=" and "-=" operators can be used with events to add or remove event handlers respectively.

  • These methods will internally call things like AddEventHandler and Delete EventHandler.

The above is the detailed content of Difference between delegates and events in C#. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!