Introduction
I have read many articles about delegation and events in C # To understand what they are and how to use them. Now I will describe the entire understanding process as follows, I am afraid you need to know every aspect I learned :-).
What is delegation?
The concepts of delegation and event fully cooperate. The delegate is just a function pointer, that is, it can reference the function and complete it through the address transfer mechanism. A delegate is a class. When you instantiate It, You need to provide a reference function and use it as a parameter of its constructor.
Each Delegate has its own signature, for example: Delegate int SomeDelegate (string s, bool B); is a Delegate declaration, here, the signature mentioned, that is to say, the SomeDelegate delegate has the string and bool type parameters and returns an int type.
As mentioned above: When you instantiate a delegate, you need to provide a reference function and use it as a parameter of its constructor. Note: The referenced function must have the same signature as the delegate.
Take a look at the following functions:
Private int SomeFunction (string str, bool bln ){...}
You can pass this function to the SomeDelegate constructor because they have similar signatures (in other words, they all have the same parameter type and number, and return the same data type ).
SomeDelegate sd = new SomeDelegate (SomeFunction );
Sd references SomeFunction. That is to say, SomeFunction has been registered by sd. If you call sd, SomeFunction will also be called. Remember: what I mean by SomeFunction, we will use it.
Now, you should know how to use the delegate so that we can continue to understand the event ......
Understanding of events
We know that in C:
L Button is a class. When we click it, a click event is triggered.
L The Clock (Timer) is also a class that triggers a tick event every millisecond.