"C #" delegate-delegate

Source: Internet
Author: User

C#delegate (Delegate)

A delegate in C # (Delegate) is similar to a pointer to a function in C or C + +. A delegate (Delegate) is a reference type variable that holds a reference to a method. References can be changed at run time.

Delegates (Delegate) are specifically used to implement events and callback methods. All delegates (Delegate) are derived from the System.Delegate class.

Declaration Delegate (Delegate)

A delegate declaration determines the method that can be referenced by the delegate. A delegate can point to a method that has the same label as its.

For example, suppose you have a delegate:

public delegate int MyDelegate (string s);

  

The above delegate can be used to refer to any one method with a single string parameter and return an int type variable.

The syntax for declaring a delegate is as follows:

Delegate <return type> <delegate-name> <parameter list>

  

Instantiating a delegate (Delegate)

Once a delegate type is declared, the delegate object must be created using the new keyword and is related to a specific method. When a delegate is created, the arguments passed to the new statement are written like a method call, but without parameters. For example:

public delegate void Printstring (string s); printstring PS1 = new Printstring (writetoscreen);p rintstring ps2 = new Print String (WriteToFile);

  

The following example demonstrates the declaration, instantiation, and use of a delegate that can be used to reference a method with an integer parameter and return an integer value.

1 usingSystem;
2 3 Delegate intNumberchanger (intn);4 namespaceDELEGATEAPPL5 {6 classtestdelegate7 {8 Static intnum =Ten;9 Public Static intAddnum (intp)Ten { Onenum + =p; A returnnum; - } - the Public Static intMultnum (intq) - { -Num *=Q; - returnnum; + } - Public Static intGetnum () + { A returnnum; at } - - Static voidMain (string[] args) - { - //Create a delegate instance -Numberchanger NC1 =NewNumberchanger (addnum); inNumberchanger NC2 =NewNumberchanger (multnum); - //To invoke a method using a delegate object toNC1 ( -); +Console.WriteLine ("Value of Num: {0}", Getnum ()); -NC2 (5); theConsole.WriteLine ("Value of Num: {0}", Getnum ()); * Console.readkey (); $ }Panax Notoginseng } -}

When the above code is compiled and executed, it produces the following results:

Value of Num:35value of num:175

Delegated Multicast (multicasting of a Delegate)

Delegate objects can be merged using the "+" operator. A merge delegate invokes the two delegates it merges. Only delegates of the same type can be merged. The "-" operator can be used to remove a component delegate from a merged delegate.

Using this useful feature of delegates, you can create a call list of methods to invoke when a delegate is called. This is called a delegated multicast (multicasting), also called multicast. The following program demonstrates multicast for a delegate:

1 usingSystem;2 3 Delegate intNumberchanger (intn);4 namespaceDELEGATEAPPL5 {6    classtestdelegate7    {8       Static intnum =Ten;9        Public Static intAddnum (intp)Ten       { Onenum + =p; A          returnnum; -       } -  the        Public Static intMultnum (intq) -       { -Num *=Q; -          returnnum; +       } -        Public Static intGetnum () +       { A          returnnum; at       } -  -       Static voidMain (string[] args) -       { -          //Create a delegate instance - Numberchanger NC; inNumberchanger NC1 =NewNumberchanger (addnum); -Numberchanger NC2 =NewNumberchanger (multnum); toNC =nc1; +NC + =Nc2; -          //Call Multicast thenc5); *Console.WriteLine ("Value of Num: {0}", Getnum ()); $ Console.readkey ();Panax Notoginseng       } -    } the}

When the above code is compiled and executed, it produces the following results:

Value of num:75

Purpose of the delegate (Delegate)

The following example demonstrates the use of a delegate. The delegate printstring can be used to refer to a method with a string as input and does not return anything.

We use this delegate to invoke two methods, the first to print a string to the console, and the second to print the string to a file:

1 usingSystem;2 usingSystem.IO;3 4 namespaceDELEGATEAPPL5 {6    classprintstring7    {8       StaticFileStream FS;9       StaticStreamWriter SW;Ten       //Delegate Declaration One        Public Delegate voidPrintstring (strings); A  -       //This method prints to the console -        Public Static voidWritetoscreen (stringstr) the       { -Console.WriteLine ("The String is: {0}", str); -       } -       //This method prints to a file +        Public Static voidWriteToFile (strings) -       { +FS =NewFileStream ("C:\\message.txt", A filemode.append, FileAccess.Write); atSW =NewStreamWriter (FS); - SW. WriteLine (s); - SW. Flush (); - SW. Close (); - FS. Close (); -       } in       //The method takes the delegate as an argument and uses it to invoke the method -        Public Static voidsendstring (printstring PS) to       { +ps"Hello World"); -       } the       Static voidMain (string[] args) *       { $printstring PS1 =Newprintstring (writetoscreen);Panax Notoginsengprintstring PS2 =Newprintstring (writetofile); - sendstring (PS1); the sendstring (PS2); + Console.readkey (); A       } the    } +}

When the above code is compiled and executed, it produces the following results:

The String Is:hello World

  

"C #" delegate-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.