How to provide function pointers in C/C ++ in C #

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.