This is the fourth day of my participation in the August More text Challenge. For details, see:August is more challenging
Delegates and events π₯
Preface π
In the previous article, I introduced the basic meaning and usage of delegates (Action, Func, Predicate) in C#
In C#, events (π ) are associated with delegates, so it’s easy to confuse the two, and when to use them
If you want to know more about delegation, you can check it out. This article will talk about what is an event π and what is the difference between an event and a delegation π
Definition of delegates and events π¬
entrust
Here again the simple definition of delegate and event.
Delegate: Delegate is a reference type that can be used to encapsulate named or anonymous methods. Delegates are like function Pointers in C++; However, delegates are type-safe and reliable.
A delegate is a type that calls a method dynamically. It is a reference type. A delegate is an abstraction and encapsulation of a method. The delegate object essentially represents a reference (that is, a memory address) to the method. Delegates allow methods to be passed as arguments. Delegates can be used to define callback methods. Delegates can link multiple methods together. This enables multiple event handlers to be started at the same time when the event is triggered. The delegate signature does not need to exactly match the method.
The event
Events: Events are special types of multicast delegates that can only be called from the class or structure (publisher class) that declares them. If other classes or structures subscribe to the event, the publisher class’s event handler method is called when it raises the event.
An event represents an object defined in C#, that is, the object that handles the notification process. In general, each occurrence of an event produces a sender and a receiver. In the.NET framework, an event is a proxy class that connects the event sender (the object that triggers the event) with the event receiver (the method that handles the event), that is, the event mechanism is implemented through the proxy class. When an event is fired, it is up to the event’s agent to notify (call) the corresponding method that handled the event
The difference between delegates and events
After briefly explaining the definitions of the two, the friends with good eyes will find that there is a sentence in the description of the event: “The event can also be counted as a special kind of delegation.” This sentence is not very accurate, but it can be understood in this way. Because of this, we need to look at delegates before we look at events. Most of the confusion is in the difference between the two. Here’s the difference between delegates and events:
The difference between delegates and events is as follows:
The difference between | entrust | The event | |
---|---|---|---|
1 | Is it a type | is | No, an event decorates an object |
2 | Can be called outside the class | is | no |
3 | Whether you can use = to assign | is | no |
For example
We will create two classes, ClassA and ClassB, which are simple, have only one method, and have the same method signature for both classes. There are delegates and events in ClassC. For the sake of demonstration, we will set access to both delegates and events to public. Next we will focus on the difference between delegate and event usage.
Class1
public class Class1
{
// Declare the delegate
public delegate void NumberChanger(int n);
// Declare the event
public static event NumberChanger changer;
public static void test()
{
changer(100);
}
static void Main(string[] args){ Class1.changer += Class2.ClassA_Test; Class1.changer += Class3.ClassA_Test; Class1.test(); }}Copy the code
Class2
class Class2
{
public static void ClassA_Test(int i)
{
Console.WriteLine("Class2:"+i); }}Copy the code
Class3
class Class3
{
public static void ClassA_Test(int i)
{
Console.WriteLine("Class3:"+i); }}Copy the code
Difference 1: Whether it is a type
class Class3
{
static void Main(string[] args)
{
// Delegate is used correctly
Class1.NumberChanger n1 = Class2.ClassA_Test;
// Event using compiler error
Class1.changer handle2 = Class2.ClassA_Test;
}
Copy the code
Error: Class1. Changer is a “field,” but is used here as a “type.
Two differences: delegates can be called outside the class in which they are declared, whereas events can only be called inside the class.
(1) Call the delegate outside the class
(2) Call events outside the class
Event “classc.say_eventhandler” can only occur to the left of += or -= (except when used from type “ClassC”)
3. Delegates can be assigned to external classes using =. Events can only be assigned to internal classes using =
From the error prompted by the compiler, we can see that the event can only be called inside the class that declared it. From the event itself, the event is generally used to inform the outside world of the change of the class itself attributes. We will assign a value to a property inside ClassC and then invoke an event to simulate external notification. The code is shown below
Conclusion π
Events are used in much the same way as delegates. An event is a delegate with an “event” modifier. By adding this modifier, part of the functionality of the delegate is neutered. With this modifier, we have more control over registration and unregistering. For an external class, it can only register and unregister itself with “+=/-=”, and the external class cannot actively trigger an event.
Delegates are typically used for callbacks, while events are used for external interfaces. For example, in observer mode, an event can be declared in the observed as an interface registered by an external observer. At the same time, the event can only be triggered within the observed, but not within the observer, thus ensuring security.
The main difference between an event and a delegate is that it cannot be called externally, but can be registered via += or -=. If the delegate variable is private, it cannot be registered externally. If it is public, then there are external ones that can be called, breaking encapsulation, so there is no way, in this case just define an event