Getting Started with C # delegate events-first: Getting Started with a delegate

Source: Internet
Author: User

Speaking of delegates, some people who are just getting started in C # feel very tall and have no contact, but in fact a lot of people have used lambda expression, in fact, lambda expression is a delegate.

About the introduction of a delegate there's a great God written in detail: Zhang Ziyang's blog in C # for delegates and events-Part.1. Follow Simin's understanding of the introduction of the commissioning

1. What is a delegate?

  A delegate is a class that defines a method's type so that it can be passed as a parameter to another method, which dynamically assigns the method to the parameter, avoids the large use of the If-else (Switch) statement in the program, and makes the program more extensible.

1.2 Delegate Classification:

1. Unicast delegation: How to bind an order

2. Multicast delegation: Binding multiple methods

2. Why use delegation

A developer can encapsulate a reference to a method in a delegate object (invoking the call of the procedure into an object, fully embodying the idea that the delegate strengthens the object-oriented programming), and then passing the delegate object to the code that needs to refer to the method, so that in the process of compiling we do not know which method is called, so that C # After introducing the mechanism of delegation, the separation of the method declaration and the method realization fully embodies the object-oriented programming idea.

3. How to use the Commission

3.1 The definition of a delegate is simple: Create a new console program first, and then do the following

(1), a new class is used to define the delegate and to make a delegate declaration

We should pay attention to one thing: The parameter type of the delegate, the number of parameters and the return value of the delegate must match the parameter type, the number of parameters and the return value of the method to be bound;

 Public classGmanage {/// <summary>        ///1. Define the delegate, which defines the type of method that can be represented/// </summary>        /// <param name= "x" ></param>        /// <param name= "y" ></param>         Public Delegate voidGreetingdelegate (intXinty); /// <summary>        ///2. Declare the DELEGATE1 variable/// </summary>         Publicgreetingdelegate delegate1; /// <summary>        ///3. The method of being called Delegate/// </summary>        /// <param name= "x" ></param>        /// <param name= "y" ></param>         Public voidSayHello (intXinty) {if(Delegate1! =NULL)//If you have a method to register a delegate variable{delegate1 (x, y);//calling a method through a delegate            }        }    }

(2), the method binding of the delegate, and the invocation

Add the following code to the console program Program.cs:

 Public classProgram { Public voidWrite1 (intXinty) {Console.WriteLine ("{0}+{1}={2}", x, y, x +y); }         Public Static voidWrite2 (intXinty) {Console.WriteLine ("{0}*{1}={2}", x, y, X *y); }        Static voidMain (string[] args) {gmanage gm=NewGmanage (); Gm.delegate1=NewProgram (). Write1;//assign a value to a variable of the delegate type firstGm.delegate1 + = Program.write2;//to bind a static method to this delegate variablegm. SayHello (1,2);//the Write1 and Write2 methods will be called successivelyConsole.readkey (); }    }

Operation, the output is as follows:

3.2 Above operation we have commissioned the operation, the main two-step operation: Declaring the delegate and the registration method (also known as the Binding method)

1. Declaration of entrustment with delegate;

2. Binding method Binding concrete method, passing the method name;

3.3 Operation as above we know that the delegate can be bound by methods, the same delegate can also be used to unbind: as follows, we only modify the main method in Program.cs.

Add the Unbind method to the original base- =

        Static voidMain (string[] args) {gmanage gm=NewGmanage (); Gm.delegate1+=NewProgram (). Write1;//assign a value to a variable of the delegate type firstGm.delegate1 + = Program.write2;//to bind a static method to this delegate variablegm. SayHello (1,2);//the Write1 and Write2 methods will be called successivelyConsole.WriteLine ("****** Unbind method Write2 after ******"); Gm.delegate1-= Program.write2;//Delegate Method Unbindgm. SayHello (1,2);//only call Write1 after unbindingConsole.readkey (); }

The result of the operation is as follows: The delegate only performed Write1.

3.4 What is a delegate chain

In other words, the multicast delegate can generate a delegate chain, with the + = and-= operators to bind and unbind the operation, multiple methods bound to the delegate variable to form a chain of delegates. When the call is made to it, the methods of all callbacks are called sequentially.

4. Summary

A delegate is a class that has a lot of benefits, such as avoiding a lot of if....else in the core approach .... Statement (or Swich switch statement), to meet the design of the OCP principle, to extend the program, with lambda expression, simplify the code, efficient programming, the implementation of loose coupling (decoupling), this in the event is more obvious and so on.

The delegation expands our cognitive face and gives us a better understanding of the breadth and depth of C #.

Code word is not easy, reproduced please indicate the source. Thank you

   

Getting Started with C # delegate events-first: Getting Started with a 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.