About delegation in C --

Source: Internet
Author: User
Try someone else. Delegation is very important

For a long time, the delegation has always been vague. The C # book I read is not very good at it. I only know that it is similar to the function pointer in C ++. I have never had a chance to use several programs, today, let's clarify: Simply put, a class needs to call methods in another class, but you don't need to know which class it comes from, as long as the parameters and return types are the same. Example: using system; namespace consoleapplication1
{
/// <Summary>
/// Summary of class1.
/// </Summary>
Class class1
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[Stathread]
Static void main (string [] ARGs)
{
Myclass. Result (1 );
Myclass. Result (2 );
Myclass. Result (3 );
Myclass. Result (4 );
}
} Public class match
{
Public static int add (int A, int B)
{
Return (A + B );
}
Public static int sub (int A, int B)
{
Return (a-B );
}
}
 
Public class sort
{
Public int min (int A, int B)
{
Return (A <B? A: B );
}
Public int max (int A, int B)
{
Return (A> B? A: B );
}
}
// Each of the two classes has two methods. Call the following method:
Public class myclass
{

Private delegate int calculate (int A, int B); // declare the delegate
Static
Calculate
Calc;
// Instantiate the delegate, which must be static. Static methods can only call static fields.

Public static void result (int c)
{
Switch (c)
{
Case 1:
Calc = new calculate (match. Add); // here, only the function name is entered, and no parameter is written.
Break;
Case 2:
Calc = new calculate (match. Add );
Break;
Case 3:
Calc = new calculate (new sort (). max); // The call methods for static and non-static functions are different.
Break;
Case 4:
Calc = new calculate (new sort (). min );
Break ;}
System. Console. writeline (calc (1, 2 ));
// Write the parameters in the real call


}
} Is just a meaning, mainly to clarify how to write. Today, I tried an example on the machine, modified it, and debugged it.

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.