A delegate is a type of reference method. Once a method is assigned to the Delegate, the delegate has the same behavior as the delegate. The use of delegate methods can have parameters and return values like any other method.
Delegation has the following features:
The delegate is similar to a C ++ function pointer, but it is type-safe.
The delegate allows passing methods as parameters.
A delegate can be used to define a callback method.
The delegate can be linked together. For example, multiple methods can be called for an event.
The method does not need to be exactly matched with the delegate signature. For more information, see covariant and inverter.
C #2.0 introduces the concept of anonymous methods, which allowCodeBlock is passed as a parameter to replace the separately defined method.
Both the delegate and interface allow the class designer to separate the type declaration and implementation. A given interface can be inherited and implemented by any class or structure. A delegate can be created for methods in any class, provided that the method complies with the delegate method signature. Interface references or delegation can be used by objects that do not understand the classes that implement this interface or delegate methods. Since these similarities exist, when should the class designer use the delegate and when should the interface be used?
Use delegation in the following cases:
When the event design mode is used.
When static methods are encapsulated.
When the caller does not need to access other attributes, methods, or interfaces in the objects that implement the method.
A convenient combination.
When the class may require multiple implementations of this method.
Use the interface in the following cases:
When there is a set of methods that may be called.
When the class only needs a single implementation of the method.
When the class using the interface wants to forcibly convert the interface to another interface or class type.
When the implemented method is linked to the type or identifier of the class: for example, compare the method.