Interview Questions---Delegates in C #

Source: Internet
Author: User

What is a C # delegate?

Before formally introducing the Commission, I would like to take a look at the example of the Commission in life-life, if we need a lawsuit, in court is the lawyer to defend us, but the lawyer really is the client's statement, this time the lawyer is a commission, the client entrusted to the object to help defend themselves. This is the example of the Commission in our life. However, the concept of delegation in C # is like a lawyer object (it can be concluded that the delegate is a class, because only the class has the concept of the object, which also shows that C # is an object-oriented language).

After describing what a delegate is in your life, now look at how delegates in C # relate to the objects in your life, and the delegate in C # is equivalent to a function pointer in C + + (if you've learned C + + to know what a function pointer is), the function pointer takes a pointer to the entry address of a function. This pointer is then implemented to manipulate the function. The delegate in C # is equivalent to a function pointer in C + +, and there is a difference between the two: the delegate is object-oriented, type-safe, is a reference type (the delegate is a class at the beginning), so when using a delegate, you first define----and--and--------- > Use delegates. The following is a concrete look at how the delegate is used:

I. Definition: delegate void MyDelegate (Type1 para1,type2 para2);

Ii. declaration: MyDelegate D;

Iii. instantiation: D =new mydelegate (obj. Instancemethod);(Pass a method to the constructor of the delegate), the first three steps are like constructing a lawyer object, the method Instancemethod is a party

Iv. passed as a parameter to the method: MyMethod (d); (Delegate implementation passes the method as a parameter to another method, the delegate is the object of a wrapper method)

V. Use the delegate in the method. The MyMethod method is like a judge, the MyMethod method calls the delegate first, the delegate calls the method Instancemethod, the process is such as the judge to the lawyer questioned, then the lawyer must know the case before the party. C # delegate is like a lawyer, really tell the case is the client (really really called is the instance method Instancemethod)

The MyMethod method is defined as follows:

Private void MyMethod (mydelegate mydelegate) {    //  use delegated     Mydelegat (ARG1,ARG2);}

Why should I use a delegate in C #?
Believe that through the above introduction, we should not be unfamiliar with the Commission, but why we need to entrust, well why to instantiate the middle of this object, why not directly in the MyMethod method call Instancemethod method, so it is not asking for trouble? For everyone to better understand why to use the delegate, below through a window form of the "Word scribe" program to explain why.

The function of the program is: Enter text in the text box below, tick "write to" in "text area 1" or "Text area 2" check box and click "Start" button, the program will automatically "copy" the text in the box to the corresponding text area. The program interface is as follows:

The traditional implementation code is:

namespaceword scribe { Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); }        Private voidButton1_Click (Objectsender, EventArgs e) {            if(checkbox1.checked = =true) {textbox1.clear ();                Textbox1.refresh (); //Call method WriteRichTextBox1 Write text to text area 1                 This.                WriteTextBox1 ();                Textbox3.focus ();            Textbox3.selectall (); }            if(checkbox2.checked = =true) {textbox2.clear ();                Textbox2.refresh (); //Call method WriteRichTextBox2 Write text to text area 2                 This.                WriteTextBox2 ();                Textbox3.focus ();            Textbox3.selectall (); }        }        Private voidWriteTextBox1 () {stringdata =TextBox3.Text;  for(inti =0; I < data. Length; i++) {Textbox1.appendtext (Data[i].                ToString ()); //Intermittent DelayDateTime now =DateTime.Now;  while(now.) AddSeconds (1) >datetime.now) {} }}Private voidWriteTextBox2 () {stringdata =TextBox3.Text;  for(inti =0; I < data. Length; i++) {Textbox2.appendtext (Data[i].                ToString ()); //Intermittent DelayDateTime now =DateTime.Now;  while(now.) AddSeconds (1) >datetime.now) {} }}}

However, we can see from the code that the WriteTextBox1 () method and WriteTextBox2 () have a different line of code (Textbox1.appendtext (data[i). ToString ()); and Textbox2.appendtext (data[i). ToString ()), the others are exactly the same, and the difference between this statement is that the control object to which the text is written is not the same, one is TextBox1 and TextBox2, and now the code is implemented function, the band we imagine, if you want to implement a text box to write more than 2, Instead of dozens of or more, do you want to write the same number of methods for writing to the text area in a few moments? This will have to write duplicate code, resulting in poor readability of the code, so that the code is a process-oriented programming, because the function is an encapsulation of the operation process, to solve this problem, naturally we think of object-oriented programming, at this point we will think of encapsulate the changed parts, and then pass the encapsulated object as an object to the method's parameters (this idea is also a design pattern-the strategy pattern, about the design pattern series will be given later ), the following is the use of delegates to re-implement the next program:

namespaceword scribe { Public Partial classForm1:form {//Defining Delegates        Private Delegate voidWritetextbox (Charch); //declaring a delegate        PrivateWritetextbox Writetextbox;  PublicForm1 () {InitializeComponent (); }        Private voidButton1_Click (Objectsender, EventArgs e) {            if(checkbox1.checked = =true) {textbox1.clear ();                Textbox1.refresh (); //instantiating a delegateWritetextbox =NewWritetextbox (WriteTextBox1); //as a parameterWRITETEXT (Writetextbox);                Textbox3.focus ();            Textbox3.selectall (); }            if(checkbox2.checked = =true) {textbox2.clear ();                Textbox2.refresh (); //instantiating a delegateWritetextbox =NewWritetextbox (WRITETEXTBOX2); //as a parameterWRITETEXT (Writetextbox);                Textbox3.focus ();            Textbox3.selectall (); }        }        Private voidwritetext (Writetextbox writetextbox) {stringdata =TextBox3.Text;  for(inti =0; I < data. Length; i++)            {                //using DelegatesWritetextbox (Data[i]); DateTime Now=DateTime.Now;  while(now.) AddSeconds (1) >datetime.now) {} }}Private voidWriteTextBox1 (Charch) {Textbox1.appendtext (ch.        ToString ()); }        Private voidWriteTextBox2 (Charch) {Textbox2.appendtext (ch.        ToString ()); }    }}

In the code implemented after the introduction of the delegate, we write the content to the text area by means of the WRITETEXT method, which performs only abstract "write-text" operations, as to what exactly the text box is written, for the program that writes the WRITETEXT method is not known, The delegate Writetextbox is like an interface (an important principle in object-oriented design principles is that, for interface programming, not for implementation programming), the difference between the operands is masked (whether the method is to write text to text area 1 or to write text as text area 2, Now I do not need to care in the method, I just need to focus on the implementation of the "writing" this operation, without having to tangle with the selection of the object of operation.

Third, what is the role of the Commission in the end? --Delegate concluding remarks

I believe that through the above two parts we also understand what a delegate is and why in C # to introduce the concept of delegation. Now summarize the introduction of the Commission after the end of the role there? From the above delegate code can be found that, after the introduction of the delegate, the programmer can encapsulate the method's reference in the delegate object (the call of the process into the object, fully embodies the delegation to strengthen the idea of object-oriented programming. ), and then pass 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 to call, so that C # introduced a delegation mechanism, so that the method declaration and method implementation separation, fully embodies the object-oriented programming idea.

Delegate to self-summary:

I am a special class , I define the type of the method, (just like int defines a number type, when a delegate object is instantiated with a method, the delegate represents a method, the type of the method is the delegate type), and I can pass the method as a parameter of another method. Makes programs easier to extend

This article is reproduced from http://www.cnblogs.com/zhili/archive/2012/10/22/Delegate.html

Interview Questions---Delegates in C #

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.