C # delegation event entry-lecture 1: delegation entry,

Source: Internet
Author: User

C # delegation event entry-lecture 1: delegation entry,

Speaking of delegation, some people who are just getting started with c # Feel very high and have never touched on it. But in fact many people have used Lambda expressions. Actually, Lambda expressions are a delegate.

For more information about delegation, see the delegation and event-Part.1 in Blog C # of Zhang Ziyang. Next we will introduce the delegation entry based on our understanding.

1. What is delegation?

  A delegate is a class that defines the type of a method so that the method can be passed as a parameter of another method. This way, the method is dynamically assigned to the parameter, it can avoid using the If-Else (Switch) statement in a large number in the program, and make the program more scalable.

1.2 delegated category:

1. unicast delegation: bind a single method

2. multicast delegate: bind multiple methods

2. Why do I use delegation?

Developers can encapsulate method references in delegate objects (converting process calls into object calls fully reflects the idea of delegate strengthening object-oriented programming ), then pass the delegate object to the code that needs to reference the method, so that we do not know which method to call during the compilation process. In this way, after C # introduces the delegate mechanism, the separation of methods and implementation fully reflects the object-oriented programming philosophy.

3. How to Use Delegation

3.1 The definition of delegation is actually very simple: first create a console program and then perform the following operations,

(1) A new class is created to define the delegate and conduct the delegate declaration.

Note that the parameter type of the delegate must be the same as the parameter type of the method to be bound;

Public class GManage {// <summary> // 1. Define the delegate, it defines the types of methods that can be represented /// </summary> /// <param name = "x"> </param> /// <param name = "y "> </param> public delegate void GreetingDelegate (int x, int y); // <summary> // 2. Declare the delegate1 variable // </summary> public GreetingDelegate delegate1; /// <summary> /// 3. Method of the called deleGATE /// </summary> /// <param name = "x"> </param> // /<param name = "y"> </param> public void SayHello (int x , Int y) {if (delegate1! = Null) // if there is a method to register the delegate variable {delegate1 (x, y); // call the method through delegation }}}

(2) delegate method binding and calling

Add the following code to the console Program. cs:

Public class Program {public void Write1 (int x, int y) {Console. writeLine ("{0} + {1} = {2}", x, y, x + y);} public static void Write2 (int x, int y) {Console. writeLine ("{0} * {1} = {2}", x, y, x * y);} static void Main (string [] args) {GManage gm = new GManage (); gm. delegate1 = new Program (). write1; // assign gm to the delegate type variable first. delegate1 + = Program. write2; // bind the delegate variable to a static method gm. sayHello (1, 2); // call the Write1 and Write2 Methods Console successively. readKey ();}}

The output result is as follows:

3.2 we performed the delegate operation for the above operations, mainly in two steps: declaring the delegate and registration method (also called the binding method)

1. Declare the delegate to use the delegate statement;

2. Bind a method to a specific method and pass the method name;

3.3 In the above operation, we know that the delegate can bind methods, and the same delegate can also unbind Methods: as follows, we only modify the main method in Program. cs.

Add the unbind method on the original basis-=

Static void Main (string [] args) {GManage gm = new GManage (); gm. delegate1 + = new Program (). write1; // assign gm to the delegate type variable first. delegate1 + = Program. write2; // bind the delegate variable to a static method gm. sayHello (1, 2); // call the Write1 and Write2 Methods Console successively. writeLine ("******* after the unbinding method Write2 ******"); gm. delegate1-= Program. write2; // unbind gm from the delegate method. sayHello (1, 2); // After unbinding, only the Write1 Console is called. readKey ();}

The running result is as follows: the delegate only executes Write1.

3.4 what is a delegated chain

In other words, a multicast delegate can generate a delegate chain and bind and unbind the strings with the + = and-= operators, bind multiple methods to the delegate variable to form a delegate chain. When calling it, all callback methods will be called in turn.

4. Summary

A delegate is a class with many benefits, such as avoiding a large number of if .... else .... statement (or swich switch statement); meets the OCP principle of program design; makes the program extensible; simplifies code and programming with Lambda expressions; implements loose coupling (decoupling) of the program ), this is obvious in events.

Delegated extension of our cognitive aspect, let us further understand the profound and profound c.

 

The code word is not easy. Please indicate the source for reprinting. Thank you.

Source code link: https://github.com/YaoHigh/DelegateDemo

 

Related Article

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.