My opinion of C # Delegation

Source: Internet
Author: User

The use of delegates is very simple, to understand the basic syntax can be open. But the real problem with delegating is that you don't know the scenario, like you've learned a new skill, but can't find any place to cast your fist. The puzzle has been holding me up until recently, as if it had dawned on me, so hurry up and jot down the idea that this may not be ripe yet. If there is any wrong idea, also hope that the garden friends correct me.

Decoupling

In fact, the most important role of the delegate is to decouple, transfer the function of the program method to define the party . Without the use of a delegate, the function and behavior of the method (what can be done) are determined by the method provider, and once the method is defined, the things that can be done are fixed, which is equivalent to the method being static. However, if the method uses a delegate parameter type, the definition of the method function is shifted, at which point the method can do what is determined by the caller of the method. This is equivalent to the method has the vitality, this vitality is the method of the caller given. And the reusability of the method has been improved, the former is to do one thing, now is to do a kind of thing. At the same time, a delegate can be seen as a parameter to a method, which avoids unnecessary judgments (because the method that is used as a parameter defines what to do and no additional judgment), simplifying the program logic.

Talk is cheap,show me the code.

method as the parameter of the method to avoid unnecessary judgment

We often encounter such a situation when we write programs. In the branch judgment, the operations in each branch can be attributed to a class of things, and the signature of the method remains consistent. Consider using delegates to eliminate these branch judgments. Suppose now to do a arithmetic function, which has four methods, their signatures are the same, accept two double input, and output a double. The general practice is to:

public enum Operate{    Add,    Subtrac,    Multip,    Divisi}public static double Calculate(double a,double b, Operate operate){    switch(operate)    {        case Operate.Add:            return Add(a, b);        case Operate.Subtrac:            return Subtrac(a, b);        case Operate.Multip:            return Multip(a, b);        case Operate.Divisi:            return Divisi(a, b);        default:            return 0;    }}public static double Add(double a , double b){    return a + b;}public static double Subtrac(double a, double b){    return a - b;}public static double Multip(double a, double b){    return a * b;}public static double Divisi(double a, double b){    if (b == 0) throw new Exception("分母不能为0");    return a / b;}

There is a drawback to this implementation, and now it is arithmetic, what if we join other types of operations later? Each addition to a type of operation to add a branch to judge, so that the maintenance costs are a bit high, also does not conform to the modification of the closed, open the opening and closing principle of expansion. If you are building a class for each type of operation, it is a bit of a fuss to solve it with polymorphic thinking. Consider using a delegate to resolve this problem by using the same delegate as the method signature instead of the parameter of the enumeration type.

First create a new delegate type with the same method signature, and then use the same delegate as the method signature instead of the enumeration type's parameters:

public delegate double CalculateDelegate(double a, double b);
public static double Calculate(double a, double b, CalculateDelegate operate){    return operate(a, b);}

The caller determines the specific operation:

static void Main(string[] args){    Calculate(1, 2, Add);    Calculate(1, 1, Divisi);}

The use of delegates to solve this problem seems very good, but there are shortcomings, the need to define a corresponding method for each type of calculation, and some of these methods are not very high frequency, the program may be a large number of such calculation methods, maintenance of these methods is not a small burden. C # provides a way for anonymous functions to solve this problem.

static void Main(string[] args){    Calculate(1, 2, delegate (double a,double b) { return a + b; });    Calculate(1, 1, delegate (double a, double b) { return a / b; });}

Well, it solves the problem above. But it seems that the code is not readable enough, then continue to evolve, C # provides a lambda expression, so that we can almost not feel the way the delegate exists, let its natural use of C # delegate, the original C # delegate is almost forgotten, the delegation three steps no longer exist, entrusted with the anonymous function = = Lambda expressions The Ultimate evolution, C # is so powerful!

You can play like this:Calculate(1, 2, (double a,double b) => { return a + b; });

You can also play this way:Calculate(1, 2, (a,b) => { return a + b; });

Method The caller decides what the method does

LINQ in C # is a delegate to the extreme, in the Where method, for example, where the method itself is only responsible for filtering the elements in the collection of things, but as to what is specific, do not care. The specific thing to do is specified by the method invocation towners, such as filtering elements greater than 10, or elements less than 5, which are determined by the caller. The flexibility and reusability of the method have been improved. Imagine if the filter criteria rule for each element is to write a new method that is identical to the other actions except the filter condition, does the mentality explode? With the parameters of the delegate type, all of this becomes simple. To do one thing becomes a kind of thing, as to which thing, method caller to decide.

The most important application in this way is the callback function.

A callback function is a function that is called through a function pointer. If you pass the pointer (address) of the function as an argument to another function , when the pointer is used to invoke the function it points to, we say this is a callback function . The callback function is not called directly by the implementing party of the function , but is invoked by another party when a particular event or condition occurs, and is used to respond to the event or condition.

Simply understood, when we pass function A to function B and B to execute a, a is a callback function (callback functions). The callback function is definitely defined by the method caller, and when the method executes, the callback function is triggered when the appropriate condition is met. The way a callback function is implemented in C # is a delegate.

Suppose now we have two methods, one method is responsible for doubling each element in the array, the other is responsible for adding 1, and now it needs doubling and adding one. If you do not use a delegate (callback function), you need to do two for loops, the performance is unacceptable, this time you can use the delegate (callback function) to solve, only need a for loop to do.

Do not use delegates (callback functions):

public static void Double(int[] nums){    for (int i = 0; i < nums.Length; i++)    {        nums[i] = nums[i] * 2;    }}public static void AddOne(int[] nums){    for (int i = 0; i < nums.Length; i++)    {        nums[i] = nums[i] + 1;    }}
static void Main(string[] args){    int[] nums = { 1, 2, 3 };    Double(nums);    AddOne(nums);}

Using delegates (callback functions):

public static void DoubleAndAddOne(int[] nums,Func<int,int> func){    for (int i = 0; i < nums.Length; i++)    {        nums[i] = func(nums[i] * 2);    }}
DoubleAndAddOne(nums, n => n + 1);

Coderfocus

Public Number:

Declaration: This article for Bo Master Learning sentiment Summary, the level is limited, if improper, welcome correction. If you think it's a good idea, click on the button below, thanks for your support. Please specify the author and source of the reference.

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.