In C #, the most flexible and hard-to-Master pointer in C and C ++ is removed. In C #, how does one provide function pointers in C/C ++? C # provides a delegate, which is a reference type inherited from the system. Delegate class. It is equivalent to the function pointer prototype. Unlike function pointers, delegate is type-safe in C #, and delegate is especially suitable for anonymous calls. To use a delegate, three steps are required: Declaration, instantiation, and call.
Using system;
// Declare a delegate named mfdelegate, which has a string-type parameter
// C # A new class will be generated during compiler compilation. This class inherits from system. Delegate, Class
// Name mfdelegate
Public Delegate void mfdelegate (string name );
Public class Hello word
{
// Define the method Hello () that has the same parameter type as mfdelegate ()
Public static void Hello (string name)
{
Console. writeline ("Hello, {0 }! ", Name );
}
// Define the goodbye () method with the same parameter type as mfdelegate ()
Public static void goodbye (string name)
{
Console. writeline ("Goodbye, {0 }! ", Name );
}
Public static void main ()
{
// Create an mfdelegate instance mf1
Mfdelegate mf1 = new mfdelegate (Hello );
// Call mf1
Mf1 ("Hello word ");
Mfdelegate mf2 = new mfdelegate (goodbye );
Mf2 ("Hello word ");
// Combine mf1 mf2 into a new delegated mf3
Mfdelegate mf3 = mf1 + mf2;
// Call mf3
Mf3 (" Program Member ");
// Delete mf1 from the composite delegate mf3
Mfdelegate mf4 = mf3-mf1;
Mf4 ("Hello word ");
}
}
program result: Hello, Hello word! // Mf1; goodbye, hello word! // Mf2
hello, programmer! Goodbye, programmer! // Mf3
goodbye, hello word! // Mf4