[C # Basic Knowledge Series] Topic 1: In-depth analysis of delegation-Why is delegation introduced in C #

introduction:

Some friends who are new to C # may not have a deep understanding of some basic features in C #. However, this knowledge is also a question often asked by interviewers during interviews, so I think it is necessary to share with some friends who are close to C #. Next article about the basic knowledge of C #, so with this series, I hope that through this series, friends can understand the basic knowledge of C # further. However, delegation is also a more important point in the basic knowledge of C #. Basically, the following features are somewhat related to delegation, so here I will talk about delegation first, why do we need to delegate.

1. What is C # delegation?

Before I formally introduce the delegation, I would like to look at the example of delegation in life-in life, if we need to sue, the lawyer will defend us in court, but the lawyer really executes the party ’s statement At this time, the lawyer is a client, and the client entrusts the lawyer to defend himself. This is the example of delegation in our lives. However, the concept of delegation in C # is like a lawyer object (from which it can be concluded that delegation is a class, because only classes have the concept of objects, which also reflects that C # is an object-oriented language).

After introducing what delegation is in life, let's take a look at how delegation in C # is related to objects in life. The delegation in C # is equivalent to a function pointer in C ++ (if you have learned C ++ before, you know what a function pointer is. Conceptual), function pointer is to use a pointer to obtain the entry address of a function, and then use this pointer to implement the operation of the function. The delegate in C # is equivalent to the function pointer in C ++, which means that the two are different: the delegate is object-oriented, type-safe, and is a reference type (it is said that the delegate is a class from the beginning), so when using the delegate The first thing to define is-> declaration-> instantiation-> passed as a parameter to the method-> use delegation. Let's take a closer look at how to use delegates:

1. Definition: delegate void Mydelegate (type1 para1, type2 para2);

2. Statement: Mydelegate d;

Three, 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 party

Four, passed as a parameter to the method: MyMethod (d); (The delegate implementation passes the method as a parameter to another method, and the delegate is an object that wraps the method)

5. Use delegation in the method. The MyMethod method is like a judge. The MyMethod method first calls the delegate, and the delegate calls the method InstanceMethod. This process is like the judge asking the lawyer a question, and then the lawyer must know the case before the client. C # commissioning is like a lawyer, who really tells the case is the party (really called the instance method InstanceMethod)

The definition of MyMethod method is as follows:

Copy code
private  void MyMethod (Mydelegate mydelegate) 

{ 
    // Use delegate 
    mydelegat (arg1, arg2); 

}
Copy code

Second, why use delegates in C #?
I believe that after the above introduction, everyone should be no stranger to delegation, but why do we need to delegate, why should we instantiate this object in the middle, and why not call the InstanceMethod method directly in the MyMethod method, so this is not self-seeking Is it troublesome? In order for everyone to better understand why delegation is used, the following uses a Window Form "text scribe" program to explain why.

The function of the program is: enter text in the lower text box, check the "text area 1" or "text area 2" check box in the "write to" combo box, and then click the "start" button, the program will automatically place the text box The text in "transcribe" to the corresponding text area. The program interface is as follows:

 The traditional implementation code is:

Copy code
namespace text scribe 
{ 
    public  partial  class Form1: Form 
    { 
        public Form1 () 
        { 
            InitializeComponent (); 
        } 

        private  void button1_Click ( object sender, EventArgs e) 
        { 
            if (checkBox1.Checked == true ) 
            { 
                textBox1.Clear (); 
                textBox1 .Refresh (); 
                // Call method WriteRichTextBox1 to write text in text area 1 
                this .WriteTextBox1 (); 
                textBox3.Focus (); 
                textBox3.SelectAll ();
            }
             
            { if(checkBox2.Checked == true ) 
            { 
                textBox2.Clear (); 
                textBox2.Refresh (); 
                // Call the method WriteRichTextBox2 to write text in the text area 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 delay
                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());
                //间歇延时
                DateTime now = DateTime.Now;
                while (now.AddSeconds(1) > DateTime.Now)
                {  }
            }
        }
    }
}
Copy code

However, we will find from the code that the WriteTextBox1 () method and WriteTextBox2 () have only one line of code that is different (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 into which the text is written is not the same, one is TextBox1 and TextBox2, and now this code is to achieve the function, let's think about the ribbon, if we want to achieve There are more than two text boxes written, but dozens or more, so will soon write the same number of methods for writing text areas? In this way, you have to write repeated code, which leads to poor readability of the code. Writing code is also a process-oriented programming method. Because the function is an encapsulation of the operation process, to solve this problem, we naturally think of facing Object programming, then we will think of the changes part of the package together, then the method parameters then encapsulated object passed as an object given (this idea is a design pattern - strategy pattern, design patterns series will As will be given later ), the following uses the delegate to re-implement this program:

Copy code
namespace text scribe 
{ 
    public  partial  class Form1: Form 
    { 
        // define the delegate 
        private  delegate  void WriteTextBox ( char ch);
         // declare the delegate 
        private WriteTextBox writeTextBox; 

        public Form1 () 
        { 
            InitializeComponent (); 
        } 

        private  void button1_Click ( object sender, EventArgs e) 
        { 
            if (checkBox1.Checked == true ) 
            { 
                textBox1.Clear ();
                textBox1.Refresh (); 
                // Instantiate the delegate 
                writeTextBox = new WriteTextBox (WriteTextBox1);
                 // As a parameter 
                WriteText (writeTextBox); 

                textBox3.Focus (); 
                textBox3.SelectAll (); 
            } 
            if (checkBox2.Checked == true ) 
            { 
                textBox2.Clear (); 
                textBox2.Refresh (); 
                // Instantiate delegate 
                writeTextBox = new WriteTextBox (WriteTextBox2);
                 // As parameter 
                WriteText (writeTextBox);
 
                textBox3.Focus ();
                textBox3.SelectAll();
            }
        }


        private void WriteText(WriteTextBox writetextbox)
        {
            string data = textBox3.Text;
            for (int i = 0; i < data.Length; i++)
            {
                // 使用委托
                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());
        }
    }
}
Copy code

Introducing the code implemented after commissioning, we use the WriteText method to write content to the text area. What it does is perform an abstract "write text" operation. As for writing text in that text box, for programs that write WriteText I do n’t know. Delegating writeTextBox is just like an interface (a very important principle in object-oriented design principles is-for interface programming, not for implementation programming), shielding the difference of operating objects (the method is to write text Writing text in area 1 is still like writing text in text area 2. Now I don't need to care in my method, I only need to focus on implementing the operation of "writing text" without having to worry about the choice of operating object).

3. What is the role of delegation? ——Commission summary statement

I believe that through the above two parts, everyone also understands what delegation is and why the concept of delegation is introduced in C #. Now let ’s sum up the role of the commission after the introduction of delegation? It can be found from the above delegate code that after the introduction of the delegate, the programmer can encapsulate the method reference in the delegate object (transforming the call of the procedure into the call of the object, which fully embodies the idea that the delegate strengthens the object-oriented programming.), Then pass the delegate object to the code that needs to refer to the method, so that we do n’t know which method was called during the compilation process. In this way, after the introduction of the delegate mechanism in C #, the separation of method declaration and method implementation fully reflects the orientation Object programming ideas.

Commissioned summary of himself:

I am a special class , I define the type of method, (just like int defines a numeric type, when a method is used to instantiate the delegate object, the delegate represents a method, the type of this method is the delegate type), I can pass the method as a parameter of another method to make the program easier to expand

 

4. Summary

The content of this topic introduction written here is also over. In some places in this topic, some knowledge of design patterns is mentioned. If a friend has not started to study design patterns, I suggest everyone to learn it, and I also I will share my understanding with you in the following series. For the next topic in this series, I will share with you the concept of the event. Finally, I hope this topic will allow you to further understand the commission.

 

http://www.cnblogs.com/zhili/archive/2012/10/22/Delegate.html

Published 28 original articles · Like 15 · Visits 110,000+

Guess you like

Origin blog.csdn.net/z3h0a5n8g8x9i9a2o3/article/details/8603561