Representative (delegate ):
It is a function pointer in the C # language, which indicates that it can point to a function and call the implementation of this function during running. Let's take a look at its implementation steps:
- Declare a delegate object.
- Implement functions with the same parameters and return values as delegate (which can be static and non-static ).
- When a delegate object is generated, pass the implemented function as a parameter to its constructor.
See the following example:
Using System;
Using System. Collections. Generic;
Using System. Text;
Namespace @ delegate
{
Public delegate void Mydelegate (string mydelegate); // declare a representative of me (step 1)
Class Program
{// Implement a function that represents the same parameters and return values (step 2)
Public void HelloDelegate (string mydelegate)
{
Console. WriteLine (mydelegate );
}
// Implement a static function that represents the same parameters and return values (step 2 ).
Public static void HelloStasticDelegate (string mydelegate)
{
Console. WriteLine (mydelegate );
Console. Read ();
}
Static void Main (string [] args) // step 3
{// Call of non-static member Methods
Program I = new Program ();
Mydelegate d = new Mydelegate (I. HelloDelegate); // The generated variable d points to the HelloDegegate function.
D ("Hello delegate"); // call
// Call the static member Method
Mydelegate dd = new Mydelegate (Program. HelloStasticDelegate );
Dd ("Hello static delegate ");
}
}
}