[C # Basic Knowledge series] Topic 1: in-depth analysis of delegation-Why to introduce delegation in C #

Source: Internet
Author: User

Introduction:

Some friends who are new to C # may not have a deep understanding of some basic features of C #. However, this knowledge is also a frequently asked question by the interviewer during the interview, so I think it is necessary to share C # basic knowledge with some friends who have been in contact with C # Soon.ArticleSo with this series, I hope that my friends can further understand the basic knowledge of C # Through this series. However, delegation is an important part of C # basic knowledge. Basically, the subsequent features are related to delegation. So let's talk about delegation first. Why do we need delegation.

I. What is C # delegation?

Before officially introducing delegation, I would like to take a look at the example of delegation in my life-if we need to go to court, lawyers will defend us in court, however, the lawyer really executes the Statement of the client. At this time, the lawyer is an entrusted object, and the client entrusts the lawyer to defend himself. This is an example of delegation in our lives. However, the concept of delegate in C # is like a lawyer.Objects (from this we can conclude that the delegate is a class, because only classes have the concept of objects, which also reflects that C # is an object-oriented language ).

After introducing what is delegate in life, let's take a look at how delegate in C # associates with objects in life, the delegate in C # is equivalent to the function pointer in C ++ (if you have learned C ++ before, you will know what the function pointer is ), the function pointer is used to obtain the entry address of a function, and then the pointer is used to perform operations on the function. The delegate in C # is equivalent to the function pointer in C ++, that is, there is a difference between the two: the delegate is object-oriented and type-safe, it is a reference type (in the beginning, the delegate is a class), so when using the delegate, you must first define --> declaration --> instantiation --> passed as a parameter to the method --> use the delegate. The following describes how to use the delegate:

1. Definition: Delegate void mydelegate (type1 para1, type2 para2 );

Ii. Declaration: mydelegate D;

Iii. instantiation: D = new mydelegate (obj. instancemethod); (pass a method to the Delegate constructor). The first three steps are like constructing a lawyer object. The method instancemethod is like a client.

4. Pass the method as a parameter: mymethod (d); (the delegate implementation transmits the method as a parameter to another method, and the delegate is the object of a packaging method)

5. Use delegation in the method. The mymethod method is like a judge. The mymethod method calls the delegate first, and the delegate calls the instancemethod method. This process is like a judge asking a lawyer. Then, the lawyer must have informed the client about the case. C # The delegate is like a lawyer. The client who really tells the case (the instance method instancemethod is called)

The mymethod method is defined as follows:

 
Private VoidMymethod (mydelegate ){//Use DelegationMydelegat (arg1, arg2 );}

Ii. Why do I use delegation in C?
I believe that after the above introduction, we should be no stranger to the delegation. However, why do we need to delegate and why do we need to instantiate this object in the middle, why not call the instancemethod method directly in the mymethod method? In order to better understand why delegates are used, the following uses a window form's "text copywriter"ProgramExplain why.

The function of the program is: Enter text in the text box below, select the "region 1" or "Region 2" check box in the "write to" combo box, and click the "Start" button, the program automatically copies the text in the text box to the corresponding text area. The program interface is as follows:

Traditional implementationCodeIs:

 Namespace  Text copywriter {  Public   Partial   Class  Form1: FORM {  Public Form1 () {initializecomponent ();}  Private   Void Button#click ( Object  Sender, eventargs e ){  If (Checkbox1.checked = True  ) {Textbox1.clear (); textbox1.refresh ();  //  Call method writerichtextbox1 to write text in partition 1                  This . Writetextbox1 (); textbox3.focus (); textbox3.selectall ();}  If (Checkbox2.checked = True  ) {Textbox2.clear (); textbox2.refresh ();  //  Call method writerichtextbox2 to write text in partition 2                  This  . Writetextbox2 (); textbox3.focus (); textbox3.selectall ();}}  Private   Void Writetextbox1 (){  String Data = Textbox3.text;  For ( Int I = 0 ; I <data. length; I ++ ) {Textbox1.appendtext (data [I]. tostring ());  //  Intermittent latency Datetime now = Datetime. now;  While (Now. addseconds ( 1 )> Datetime. Now ){}}}  Private   Void  Writetextbox2 (){  String Data = Textbox3.text;  For ( Int I = 0 ; I <data. length; I ++ ) {Textbox2.appendtext (data [I]. tostring ());  //  Intermittent latency Datetime now = Datetime. now;  While (Now. addseconds ( 1 )> Datetime. Now ){}}}}} 

However, from the code, we can find that the writetextbox1 () method and writetextbox2 () have only one line of code (textbox1.appendtext (data [I]. tostring (); and textbox2.appendtext (data [I]. tostring ();), the others are the same, and the difference of this statement is that the control objects written to the text are different. One is textbox1 and textbox2, now the code implements the function. Let's imagine that if we want to write more than two text boxes, but dozens or more, so soon I will write the same number of methods for writing data into the primary area? In this way, you have to write repeated code, resulting in poor code readability.Process-orientedIs a programming method, because the function is an encapsulation of the operation process, to solve this problem, we naturally thinkObject-orientedProgramming, now we will thinkEncapsulate the changed part, and then pass the encapsulated object as an object to the parameters of the method (this idea is also a design pattern-policy pattern,The design pattern series will be provided later),Next we will use the delegate to re-implement this program:

Namespace  Text copywriter {  Public   Partial   Class  Form1: FORM {  //  Define Delegation          Private   Delegate   Void Writetextbox ( Char  Ch );  //  Delegate Declaration          Private Writetextbox;  Public  Form1 () {initializecomponent ();}  Private   Void Button#click ( Object  Sender, eventargs e ){  If (Checkbox1.checked = True  ) {Textbox1.clear (); textbox1.refresh ();  //  Instantiate Delegation Writetextbox = New  Writetextbox (writetextbox1 );  //  As a parameter  Writetext (writetextbox); textbox3.focus (); textbox3.selectall ();}  If (Checkbox2.checked = True  ) {Textbox2.clear (); textbox2.refresh ();  //  Instantiate Delegation Writetextbox = New Writetextbox (writetextbox2 );  //  As a parameter  Writetext (writetextbox); textbox3.focus (); textbox3.selectall ();}}  Private   Void  Writetext (writetextbox ){  String Data = Textbox3.text;  For ( Int I = 0 ; I <data. length; I ++ ){  //  Use Delegation  Writetextbox (data [I]); datetime now = Datetime. now;  While (Now. addseconds ( 1 )> Datetime. Now ){}}}  Private   Void Writetextbox1 ( Char Ch) {textbox1.appendtext (ch. tostring ());}  Private   Void Writetextbox2 ( Char  Ch) {textbox2.appendtext (ch. tostring ());}}} 

In the Code implemented after delegation, we use the writetext method to write content to the development area. It only performs the abstract "write text" operation. As for writing text like that text box, I don't know how to compile the writetext method program. Entrusting writetextbox is like an interface. (an important principle in object-oriented design principles is interface-oriented programming, it does not implement programming), and shields the differences between the operation objects (whether the method is to write text to partition 1 or write text like partition 2, now I do not need to worry about it in the method, I only need to focus on implementing the "writing text" operation, without having to tangle with the choice of operation objects ).

Iii. What is the role of delegation? -- Delegate summary statement

I believe that through the above two parts, we also understand what delegation is and why the concept of delegation should be introduced in C. Now, let's summarize what the role of delegation is after it is introduced? From the preceding delegated code, it can be found that after the delegate is introduced, the programmer can encapsulate the method reference in the delegate object (convert the call of the process to the call of the object, it fully embodies the idea of entrusting and 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.

Delegation's summary:

I amSpecial ClassI have defined the type of the method. (just like int defines the numeric type, when a delegate object is instantiated using a method, this delegate represents a method, the type of this method is the delegate type). I can pass the method as a parameter of another method, making it easier for the program to expand.

 

Iv. Summary

The content introduced in this topic is over. In this topic, some knowledge about design patterns has been mentioned in some places. If a friend has not started learning about the design patterns, it is recommended that you learn it and I will share my understanding with you in the subsequent series. For the next topic of this series, I will share with you what kind of concept I understand about events. Finally, I hope this topic will allow you to further understand the delegation.

 

 

 

 

 

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.