What are the differences between delegates and an events? Don't both hold references to functions that can be executed?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
What a great misunderstanding between events and delegates!!! A delegate specifies a TYPE (such as a
class
, or aninterface
does), whereas an event is just a kind of MEMBER (such as fields, properties, etc). And, just like any other kind of member an event also has a type. Yet, in the case of an event, the type of the event must be specified by a delegate. For instance, you CANNOT declare an event of a type defined by an interface.Concluding, we can make the following Observation: the type of an event MUST be defined by a delegate. This is the main relation between an event and a delegate and is described in the section II.18 Defining events of ECMA-335 (CLI) Partitions I to VI:
However, this fact does NOT imply that an event uses a backing delegate field. In truth, an event may use a backing field of any different data structure type of your choice. If you implement an event explicitly in C#, you are free to choose the way you store the event handlers (note that event handlers are instances of the type of the event, which in turn is mandatorily a delegate type---from the previous Observation). But, you can store those event handlers (which are delegate instances) in a data structure such as a
List
or aDictionary
or any other else, or even in a backing delegate field. But don’t forget that it is NOT mandatory that you use a delegate field.Here is another good link to refer to. http://csharpindepth.com/Articles/Chapter2/Events.aspx
Briefly, the take away from the article - Events are encapsulation over delegates.
Quote from article:
Delegate is a type-safe function pointer. Event is an implementation of publisher-subscriber design pattern using delegate.
An Event declaration adds a layer of abstraction and protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.
Covariance
andContravariance
provide extra flexibility to the delegate objects. On the other hand, an event has no such concepts.Covariance
allows you to assign a method to the delegate where the return type of the method is a class which is derived from the class that specifies the return type of the delegate.Contravariance
allows you to assign a method to the delegate where the parameter type of the method is a base class of the class that is specified as the parameter of the delegate.