Document directory
- 1. What is delegation?
- 2. What is an event?
- Iii. Use Delegation
This topic is about delegation.
1. What is delegation?
The delegate is a function pointer defined by delegate (not just a pointer, but contains a set of related data ). The delegate type defines the delegate variables. The delegate variables can be assigned with "function names", anonymous functions, and lambda values. The delegate variable can call this function.
2. What is an event?
Events are the encapsulation of delegation, similar to attribute encapsulation of fields.
The restrictions imposed by the event are: 1. Specify the delegate type, void (Object, EventArgs or its subclass ); 2. Only add join Function + = operation and reduce join function-= operation are provided externally, but no interface for obtaining the delegate variable is provided to prevent arbitrary modification.
You only need to add the event keyword before defining the delegate variable to define the event. The delegate of the standard event is EventHandler <T>. The compiler automatically generates the relevant packaging code. However, you can also customize the packaging code:
Event Delegate type event name {add {}remove {}}
Iii. Use Delegation
The first step is to define the delegate type, the second step is to define the delegate variable, and the third step is to execute the delegate.
1. int delegate myFunc (int, int );
2. myFunc f1, f2;
F1 = (x, y) => x + y;
F2 = delegate (int x, int y) {return x * y ;};
3. f1 (1, 2); // = 3
F2 (1, 2); // = 2
Application of delegation: When you need to pass parameters to a process, you can select a specific algorithm or notify the object for processing.
An event is the purpose of the notification object to process messages. The message publisher defines the event (delegate), and the subscriber binds the event processing function. When the publisher decides to trigger an event, the subscriber calls the Bound event processing function to perform related operations.
The publisher does not need to know how to handle the event. The publisher only needs to determine the time when the event is triggered, and the subscriber does not need to know how the event occurs. Instead, the publisher only needs to simply associate the event and provide a solution.