Jing: Why should delegates be introduced in C#

Introduction:

For some friends who are new to C#, they may not have a deep understanding of some basic features in C#. However, this knowledge is also a question that interviewers often ask during interviews, so I think it is necessary to share with some friends who have not been in contact with C# for a long time. The next article is about the basic knowledge of C#, so with this series, I hope that through this series, friends can further understand the basic knowledge of C#. However, delegation is an important point in the basic knowledge of C#. Basically, the following features are related to delegation, so here I will talk about delegation first, and why we need delegation.

1. What is a C# delegate?

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

After introducing what a delegate is in life, now let’s see how the delegate in C# is related to the 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 is the concept of a function pointer), the function pointer is to use the pointer to obtain the entry address of a function, and then use this pointer to realize the operation of the function. The delegate in C# is equivalent to the function pointer in C++, that is to say, there is a difference between the two: the delegate is object-oriented, type-safe, and is a reference type (it is said that the delegate is a class at the beginning), so when using When entrusting, you must first define –> declare –> instantiate –> pass as a parameter to the method –> use the delegate. Let’s take a look at how to use delegates in detail:

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

2. Statement: Mydelegate d;

3. Instantiation: d = new Mydelegate(obj.InstanceMethod); (pass a method to the entrusted constructor), the first three steps are like constructing a lawyer object, and the method InstanceMethod is like the client

4. Pass to the method as a parameter: MyMethod(d);

5. Use delegates in methods. The MyMethod method is like a judge. The MyMethod method calls the delegate first, and the delegate calls the method InstanceMethod. This process is like a judge asking a lawyer. The lawyer must have learned about the case from the client before. C# entrustment is like a lawyer, and the person who really tells the case is the party (the instance method InstanceMethod is really called)

The MyMethod method is defined as follows:

private void MyMethod(Mydelegate mydelegate)
{
    // use delegate
    mydelegat(arg1,arg2);
}

Second, why use delegation in C#?
I believe that after the above introduction, everyone should no longer be unfamiliar with delegates, but why do we need delegates, why should we instantiate the object in the middle, and why not call the InstanceMethod method directly in the MyMethod method, this is not self-inflicted Is it troublesome? In order for everyone to better understand why delegates should be used, let me explain why through a Window Form “text scribe” program.

The function realized by the program is: input text in the text box below, check the “Text Area 1” or “Text Area 2” check box in the “Write to” combo box and click the “Start” button, the program will automatically write the text box The text in “copy” to the corresponding text area. The program interface is as follows:

fd2fe632c79aa2741707a1a39b223b39.png

The traditional implementation code is:

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 to text area 1
                this. WriteTextBox1();
                textBox3. Focus();
                textBox3. SelectAll();
            }
            if (checkBox2. Checked == true)
            {
                textBox2. Clear();
                textBox2. Refresh();
                // Call method WriteRichTextBox2 to write text to 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());
                //intermittent delay
                DateTime now = DateTime. Now;
                while (now. AddSeconds(1) > DateTime. Now)
                { }
            }
        }
    }
}

However, we will find from the code that the WriteTextBox1() method and WriteTextBox2() are only one line of code different ( textBox1.AppendText(data[i].ToString()); and textBox2.AppendText(data[i].ToString()) ;), the others are exactly the same, and the difference of this statement is that the control objects to which text is written are different, one is TextBox1 and TextBox2, and now the code realizes the function. There are not only 2 text boxes to be written, but dozens or even more, so will the same number of methods for writing to the text area be written soon? In this way, you have to write repetitive code, which leads to poor readability of the code. Writing code in this way is also a process-oriented programming method, because the function is an encapsulation of the operation process. To solve this problem, naturally we think of object-oriented programming, at this time we think of encapsulating the changed part, and then passing the encapsulated object as an object to the parameter of the method (this Thought is also a design pattern – strategy pattern, about the design pattern series will be given later ), Let’s use delegation to re-implement this program:

namespace text scribe
{
    public partial class Form1 : Form
    {
        // define delegate
        private delegate void WriteTextBox(char ch);
        // Declare 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 parameter
                WriteText(writeTextBox);


                textBox3. Focus();
                textBox3. SelectAll();
            }
            if (checkBox2. Checked == true)
            {
                textBox2. Clear();
                textBox2. Refresh();
                // Instantiate the 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 ++ )
            {
                // use delegate
                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 the introduction of the delegate, we use the WriteText method to write content to the text area, and what it performs is only an abstract “write text” operation. As for the text box to write text, for the program that writes the WriteText method I don’t know, entrusting writeTextBox is like an interface (a very important principle in the object-oriented design principle is – programming for the interface, not for the implementation), shielding the difference of the operation object (the method is to write to the text Writing text in area 1 is still like writing text in text area 2. Now I don’t need to care about it in the method. I only need to focus on implementing the operation of “writing text” without worrying about the selection of the operation object).

3. What is the function of entrustment? –Commissioned 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 summarize what exactly does it do after the introduction of delegation? From the above delegate code, it can be found that after the delegation is introduced, the programmer can encapsulate the reference of the method in the delegate object (converting the call of the process into the call of the object fully reflects 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 don’t know which method is called during the compilation process. In this way, after C# introduces the delegation mechanism, the separation of method declaration and method implementation fully reflects the oriented Object programming ideas.

The commission summarizes itself:

I am a special class, I define the type of the method, (just like int defines the number type, when instantiating a delegate object with a method, this delegate represents a method, this method The type is the delegate type), I can pass the method as a parameter of another method, making the program easier to expand

Four. Summary

The content of this topic introduction is over here. In this topic, some knowledge of design patterns is mentioned in some places. If there are friends who have not started learning design patterns, I suggest everyone to learn, 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 what kind of concept I understand the event is. Finally, I hope this topic can give you a better understanding of entrustment.

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

Copyright statement: This article is collected or provided by netizens and is for learning and communication purposes only. If there is any infringement, please tell the moderator or leave a message, and this official account will be deleted immediately.

– EOF –

Technical group: Add Xiaobian WeChat dotnet999

Official account: dotnet lecture hall