C # Delegate

Source: Internet
Author: User

1. What is a delegate?
A: A delegate can substitute a method as a parameter into another method. Delegates (Delegate) are specifically used to implement events and callback methods. All the delegates (Delegate) are
Derived from the System.Delegate class. The simplicity of the delegate can be the method as a method, but also the commission as a parameter.

2. How to use

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 (stringnewnew printstring (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.

usingSystem;Delegate intNumberchanger (intn);namespacedelegateappl{classTestdelegate {Static intnum =Ten;  Public Static intAddnum (intp) {num+=p; returnnum; }       Public Static intMultnum (intq) {num*=Q; returnnum; }       Public Static intGetnum () {returnnum; }      Static voidMain (string[] args) {         //Create a delegate instanceNumberchanger NC1 =NewNumberchanger (Addnum); Numberchanger NC2=NewNumberchanger (Multnum); //To invoke a method using a delegate objectNC1 ( -); Console.WriteLine ("Value of Num: {0}", Getnum ()); NC2 (5); Console.WriteLine ("Value of Num: {0}", Getnum ());      Console.readkey (); }   }}

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

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:

usingSystem;Delegate intNumberchanger (intn);namespacedelegateappl{classTestdelegate {Static intnum =Ten;  Public Static intAddnum (intp) {num+=p; returnnum; }       Public Static intMultnum (intq) {num*=Q; returnnum; }       Public Static intGetnum () {returnnum; }      Static voidMain (string[] args) {         //Create a delegate instanceNumberchanger NC; Numberchanger nc1=NewNumberchanger (Addnum); Numberchanger NC2=NewNumberchanger (Multnum); NC=nc1; NC+=Nc2; //Call Multicastnc5); Console.WriteLine ("Value of Num: {0}", Getnum ());      Console.readkey (); }   }}

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

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:

usingSystem;usingSystem.IO;namespacedelegateappl{classprintstring {StaticFileStream FS; StaticStreamWriter SW; //Delegate Declaration       Public Delegate voidPrintstring (strings); //This method prints to the console       Public Static voidWritetoscreen (stringstr) {Console.WriteLine ("The String is: {0}", str); }      //This method prints to a file       Public Static voidWriteToFile (strings) {FS=NewFileStream ("C:\\message.txt", Filemode.append, FileAccess.Write); SW=NewStreamWriter (FS); Sw.         WriteLine (s); Sw.         Flush (); Sw.         Close (); Fs.      Close (); }      //The method takes the delegate as an argument and uses it to invoke the method       Public Static voidsendstring (printstring PS) {PS ("Hello World"); }      Static voidMain (string[] args) {printstring PS1=Newprintstring (Writetoscreen); printstring PS2=Newprintstring (WriteToFile);         Sendstring (PS1);         Sendstring (PS2);      Console.readkey (); }   }}

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

is: Hello world

Instance method Proxy:

 Public Delegate voidDogreeting (stringname);  Public classGreeting {/// <summary>        ///delegate (method of proxy)/// </summary>        /// <param name= "name" ></param>        /// <param name= "markgreeting" ></param>         Public voidMarkgreeting (stringname, dogreeting markgreeting)        {markgreeting (name); }        /// <summary>        ///say hello in English/// </summary>        /// <param name= "name" ></param>         Public  voidGreetingenglish (stringname) {Console.WriteLine (name+"hello!"); }        /// <summary>        ///Greet in Chinese/// </summary>        /// <param name= "name" ></param>         Public voidGreetingchinese (stringname) {Console.WriteLine (name+"Hi there!"); }    }    classProgram {[STAThread]Static voidMain (string[] args) {Greeting Greetingobj=Newgreeting (); Greetingobj.markgreeting ("Zhang San", Greetingobj.greetingenglish); Greetingobj.markgreeting ("John Doe", Greetingobj.greetingchinese); }

Reprint: Http://www.runoob.com/csharp/csharp-delegate.html and Http://www.jb51.net/article/45822.htm

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.