First, let me talk about my understanding of delegation and events, and then reference jimmy. zhang's examples of delegation and events hope to help friends who are not very clear about delegation and events.
My understanding:
Delegate:
1. A delegate is a class that defines the type of a method so that the method can be passed as a parameter of another method. In this way, the method is dynamically assigned to the parameter, it can avoid using the If-Else (Switch) statement in a large number in the program, and make the program more scalable.
2. The delegate only defines the prototype of a method. Its implementation includes:
- Declare delegate type
- Define methods that match the delegate type
- Declare delegate variable
- Initialize delegated instance
- Call delegate
3. Note: defining a delegate refers to defining a new class. The delegate implementation is derived from the base class System. multicastDelegate class, System. multicastDelegate is also derived from the base class System. delegate. C # The Compiler knows this class and uses its delegate syntax. Therefore, we don't need to know more about this internal implementation. This is how C # works with the base class to make programming easier.
4. Note: there is a problem in terms of terms. There are two different terms for a class: 'class' indicates a wide range of definitions, and 'object' indicates an instance of the class, however, there is only one term for delegation. When you create a delegated instance, the created delegated instance is still called a delegate.
5. An instance with a given delegate can represent an instance method or a static method on any object of any type-as long as the signature of the method matches the delegate.
Event:
1. The event handler cannot return values.
2. The event registration method is similar to the multicast delegate. The multicast delegate is executed in the order when the method is registered, but the event does not exist. The method execution sequence cannot be estimated.
3 ,. NET. It is recommended that the event Delegate should have no return value, and there are two parameters: object and EventArgs. the first parameter indicates the object that triggers the event, and the second parameter indicates the object that contains other useful information about the event, which can record the event occurrence. you can directly use the EventHandler provided by the system.
4. Although the public modifier is used to declare an event, it is still converted to private when compiled into IL.
5. Events are further encapsulated by delegation.
The essence of others:
I think everyone knows some examples of delegation and events on the Internet. I think jimmy zhang is the best in writing this article, and it is the easiest to make friends who are not very clear about delegation and events suddenly open up. Address: http://www.cnblogs.com/jimmyzhang/archive/2007/09/23/903360.html