Summary of delegation learning (1) Talking about the understanding of C# delegation

To understand delegation, we first need to know the concept of delegation:

"A delegate is a class that defines the type of a method so that a method can be passed as a parameter to another method. This way of dynamically assigning a method to a parameter can avoid a lot of use of If-Else in the program. (Switch) statement, while making programs more scalable."

This is a concept found on Baidu and many textbooks, but if you are a beginner in this programming language, or if you have a poor foundation, you will definitely be confused when you see this sentence. Don't worry, let's take it slow. Understand the concept of delegation through code

(1) First create a new console program. For beginners, the console program is the best tool to learn basic knowledge

copy code
//delegate void EvenHandler(object sender, EventArgs e);
    public delegate void MyDel();//Customize a delegate
    class Program
    {
        static void Main(string[] args)
        {
            //(1) Simple delegation
            MyDel say1 = SayHi;
            MyDel say2 = new MyDel(SayHi);
            say1 ();
            say2();
        }
        static void SayHi()
        {
            Console.WriteLine("Hi World");
        }
    }
copy code

This is the simplest delegate instance. The delegate can be called in the above two ways: say1 and say2. Here we need to know that the delegate is also a type , so it is at the same level as the class. You can use the delegate to use the method. Mistakenly think that the delegate and the method are at the same level, the method is only a member of the class, and the definition delegate and the corresponding method must have the same method signature, that is, the number of parameters, the same type, and the same return value type , the above code example has nothing The actual meaning, but we know the structure of the delegate and the relationship between the delegate and the method

(2) Extension of delegation

copy code
// customize a delegate
        public delegate int Expression(int a, int b);
        class Program
        {
            static void Main(string[] args)
            {
                //(2) Delegate extension
                //Expression ex = GetEX;
                //Calculate(ex, 25, 10);
                Calculate(GetAdd, 25, 10);
            }
            static int Add(int a, int b)
            {
                return a + b;
            }
            static int Divide(int a, int b)
            {
                return a / b;
            }
            static int subtract(int a, int b)
            {
                return a - b;
            }
            static int multiply(int a, int b)
            {
                return a * b;
            }
            static int GetAdd(int a, int b)
            {
                return a + b;
            }
            static void Calculate(Expression ex, int a, int b)
            {
                Console.WriteLine(ex(a, b) + "\n");
            }
        }
copy code

Compared with before, the code is a little more complicated. Above we really realized "passing or calling the method as a parameter in another method", and realized a simple addition method. Of course, we also wrote subtraction, multiplication , the method of division. What's the benefit of writing this, you wonder? Wouldn’t it be the end of me to directly call my own addition, subtraction, multiplication and division methods? What is the meaning of delegation? Here, please listen to my first thought: "The above Calculate method has relatively little code, only a simple output statement, and we only want to simply achieve a simple addition, subtraction, multiplication and division effect, so you will feel a bit many times. One move can also be said to be multiple times, but you can imagine that if we add, subtract, multiply and divide methods, the amount of code is very large, but the code similarity of these methods is very high, but each There are only one or two small statement blocks in the method that are different. It will not make you feel very uncomfortable and want to integrate them. How to deal with it? You may first want to pass the if, else if or switch statement to the Different parts of the code block are processed differently. Now I only need to do four cases of addition, subtraction, multiplication and division. This idea is acceptable for the time being. In the future, I will add remainder operations, square operations, exponential logarithmic operations, etc. Hundreds or more of such similar methods, then do I have to write hundreds of if, else, it is obvious that the scalability of the program will be very poor. So we have to change our thinking, we can use one method to put The same part is encapsulated, and different parts are passed through parameters , but the method cannot be passed and called directly as a parameter, so what should we do?, then the role of delegation is reflected at this time, we can delegate Pass it as a parameter to the encapsulated method, and call the method dynamically through the delegate ." Combined with what I said, the encapsulated part above is similar to our Calculate method, and the different part is each addition, subtraction, multiplication and division method. , you can assume that Calculate is a very large method that has been encapsulated, and what we pass in is only the part of the method that needs to be dynamically changed, so this is the so-called " method dynamically assigns parameters to the top concept"", the advantage of writing this way is to greatly improve the flexibility and extensibility of the method, and also reduce the redundancy of the code, so delegation is a very useful tool in actual projects, it can make your code more "comfortable, Robust". Do you feel that your understanding of delegation has grown so much? Later, I will continue to write about learning about anonymous methods, lambda expressions, generic delegation, and events. The above remarks are my own reference. Information, and the summary made by myself after the actual project, if there is anything wrong, I hope you can point out ^^.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324889441&siteId=291194637