C # Delegate

Source: Internet
Author: User

Tag: Call the color console to understand the keyword variable Hello logs wrapper

Basic steps

(1) Defining a delegate type, which defines a definition similar to a method, is just one more delegate;

(2) Instantiation of the delegate, the delegate is also a class type, so use the New keyword is also instantiated;

The instantiation of a delegate takes a method name as a parameter, and the definition of the method must conform to the definition of the delegate;

The number of arguments, the type of the parameter, the return type, and the delegate

(3) The object that is instantiated by the delegate is passed to other methods or directly executes the delegate (in essence, the method of executing the delegate wrapper);

A C # delegate can be understood as a wrapper for a function, and he can pass the method as a parameter to another method

Cases:

1 classHelloWorld2    {3       //Define the delegate type, which defines the definition of a similar method, just a delegate;4       Delegate voidMyDelegate (intAintb);5       Static voidMain (string[] args)6       {7          //declaring and instantiating delegate variables8MyDelegate mydelegate=NewMyDelegate (NewHelloWorld (). ADD);9          //passing an instantiated object MyDelegate as a parameter to a methodTen          NewHelloWorld (). Go (mydelegate); One Console.readkey (); A       } -       voidADD (intA=0,intb=0) -       { theConsole.Write ("This sum is {0}", A +b); -       } -        Private voidGo (mydelegate mydelete) -        { +            //invoking a delegate in a method -Mydelete (Ten, -); +        } A}

The result is:

C # Delegate

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.