Essentially, a delegate is a type-safe object pointing to several methods (similar to a C ++ function pointer ). The maintenance of a delegate has three important information: 1. Address 2 of the method to be called, parameter 3 of the method (if any), and return value of the method (if any ). Unlike C ++ function pointers,. NetThe delegate can point to static methods and instance methods.
First, let's take a look at how to define a delegate (using keywordsDelegate)
- // This delegate can point to any method that receives two int parameters and returns the int value.
- // Binary operation
- Public Delegate int binaryop (int x, int y );
When you declare this binaryop delegate, the compiler will generate such a class for you:
- Sealed class binaryop: system. multicastdelegate
- {
- Public binaryop (object target, uint functionaddress );
- Public int invoke (int x, int y );
- Public iasyncresult begininvoke (int x, int y,
- Asynccallback CB, object State );
- Public int endinvoke (iasyncresult result );
- }
Among them, invoke is the core method. As the name suggests, it is used to call every method maintained in the delegate. Begininvoke () and endinvoke () are used to call the current method asynchronously. This requires that you have a multi-threaded programming background, which is beyond the scope described in this article. Here, you only need to understand that the delegate actually secretly implements the function that would have to be implemented using multiple threads.
To be continued ......
I may feel a bit confused when I first recognize the delegation. Now let's take a complete example:
- Namespace simpledelegate
- {
- // This delegate can point to any method that receives two int parameters and returns the int value.
- // Binary operation
- Public Delegate int binaryop (int x, int y );
- // This class contains the method to be pointed to by binaryop
- //
- Public class simplemath
- {
- Public static int add (int x, int y)
- {Return X + Y ;}
- Public static int subtract (int x, int y)
- {Return x-y ;}
- }
- Class Program
- {
- Static void main (string [] ARGs)
- {
- Console. writeline ("****** simple delegate example ****** \ n ");
- // Create a binaryop object pointing to simplemath. Add ()
- //
- Binaryop B = new binaryop (simplemath. Add );
- // Call the add () method and indirectly use the delegate object.
- Console. writeline ("10 + 10 is {0}", B (10, 10 ));
- Console. Readline ();
- }
- }
- }