C # -- delegate (1 ),

Source: Internet
Author: User

C # -- delegate (1 ),

What is delegation?
Do you still remember the function pointers in C/C ++? The delegate is his "upgraded version".
Let's first look at a simple Applet:

1 # include <stdio. h> 2 3 typedef int (* Calc) (int a, int B); // use typedef to define it as a data type 4 5 int Add (int a, int B) 6 {7 int result = a + B; 8 return result; 9} 10 11 int main (void) 12 {13 int x = 100; 14 int y = 200; 15 int z = 0; 16 17 z = Add (x, y); // directly call 18 printf ("% d + % d = % d \ n", x, y, z); 19 20 Calc cFun = & Add; // indirect call 21 z = cFun (x, y ); 22 printf ("% d + % d = % d \ n", x, y, z); 23 24 return 0; 25}

 

Direct and indirect calls have the same running results.
What are variables and functions?
A variable (representing data) is the value stored in a memory segment starting from the memory address corresponding to the variable name.
A function (representing an algorithm) is a group of machine language commands stored in memory starting from the memory address corresponding to the function name.
If you know what variables and functions are, let's take a look at what direct and indirect calls are.
Direct call: The function is called by the function name. The CPU uses the function name to directly obtain the address of the function and start execution. After the function is executed, the CPU returns to the caller for further execution.
Indirect call: Call a function using a function pointer. The CPU reads the value stored by the function pointer (the address corresponding to the function name) to obtain the address of the function and start execution, finally, return to the caller for further execution.
Let's take a look at what delegation is.

1 namespace DelegateExample_Action _ 2 {3 class Program 4 {5 static void Main (string [] args) 6 {7 Calculator calculator = new Calculator (); 8 Action action = new Action (calculator. report); 9 action. invoke (); // indirect reference 10/* 11 can also write 12 action (); 13 */14 calculator. report (); // directly reference 15 // The running results are exactly the same 16} 17} 18 19 class Calculator20 {21 public void Report () 22 {23 Console. writeLine ("I have three methods. "); 24} 25 public int Add (int a, int B) 26 {27 int result = a + B; 28 return result; 29} 30 public int Sub (int, int B) 31 {32 int result = a-B; 33 return result; 34} 35} 36}

 

IDE prompts that you want to put a method with a return value of void type and an empty parameter list, the Report method is used in the Calculator class, so we put the Report method in.

Running result:

The first line is the statement printed when we call it directly, and the second line is the statement printed with the Action delegate.
To call the Add or Sub method, use the Func delegate:

 1 namespace DelegateExample_Func_ 2 { 3     class Program 4     { 5         static void Main(string[] args) 6         { 7             Calculator calculator = new Calculator(); 8  9             Func<int, int, int> Func1 = new Func<int, int, int>(calculator.Add);10             Func<int, int, int> Func2 = new Func<int, int, int>(calculator.Sub);11             int x = 100;12             int y = 30;13             int z = 0;14             z = Func1.Invoke(x, y);15             Console.WriteLine(z);16             z = Func2.Invoke(x, y);17             Console.WriteLine(z);18         }19     }20 21     class Calculator22     {23         public int Add(int a, int b)24         {25             int result = a + b;26             return result;27         }28         public int Sub(int a, int b)29         {30             int result = a - b;31             return result;32         }33     }34 }

 

When the angle brackets are closed, IDE prompts that we have 17 reloads. By turning them down, we will find that it will increase the number of parameters (the last one is the return value type ), we need to reference the Add and Sub methods. The two methods have two parameters, so we chose the case in the image, because the two parameters are of the int type, therefore, the returned result must be of the int type, so Func <int, int, int> (Calculator. add); (the first two in angle brackets are parameter types, and the last one is the return value type)

Running result:


Custom Delegation
The above Action delegate and Function delegate have been prepared by Microsoft for us. How do we declare them? This is the next custom delegate.
First, the delegate is a class. Therefore, the delegate declaration is in the namespace, which is equal to the program class. How can I check whether a delegate is a class? A very simple small program:

 1 namespace DelegateExample_IsClass_ 2 { 3     class Program 4     { 5         static void Main(string[] args) 6         { 7             Type t = typeof(Action); 8             Console.WriteLine(t.IsClass); 9         }10     }11 }

 

True indicates that the delegate is indeed a class.
Then we declare a delegate. The format of the delegate statement is as follows:
Accessable delegate keywords target method return value type delegate name (parameter list of target method );
Let's look at a small program:

 1 namespace DelegateExample_custom_delegate_ 2 { 3     public delegate double Calc(double x,double y); 4  5     class Program 6     { 7         static void Main(string[] args) 8         { 9             Calculator calculator = new Calculator();10             Calc calc = new Calc(calculator.Add);11             Calc calc2 = new Calc(calculator.Sub);12             Calc calc3 = new Calc(calculator.Mul);13             Calc calc4 = new Calc(calculator.Div);14 15             double a = 100;16             double b = 200;17             double c = 0;18 19             c = calc.Invoke(a, b);20             Console.WriteLine(c);21             c = calc2.Invoke(a, b);22             Console.WriteLine(c);23             c = calc3.Invoke(a, b);24             Console.WriteLine(c);25             c = calc4.Invoke(a, b);26             Console.WriteLine(c);27 28         }29     }30     class Calculator31     {32         public double Add(double x, double y)33         {34             return x + y;35         }36         public double Sub(double x, double y)37         {38             return x - y;39         }40         public double Mul(double x, double y)41         {42             return x * y;43         }44         public double Div(double x, double y)45         {46             return x / y;47         }48     }49 }

 

In this program, we declare a delegate called Calc, because our methods are double parameters, the return value of double, so it is "double Calc ". The rest is no big problem.
Pay attention to the following points during custom delegation:
The delegate and the encapsulated method must be "Type compatible", that is
The Data Types of the returned values must be consistent.
The parameter list is consistent in the number and data type (the parameter name does not need to be the same)
In addition, the statement must be declared at the correct position and be declared in the namespace (equal to the program level), but the nested type can exist in C, declarations are compiled in the Program class, but do not do this. Put them in the namespace at the same level as other classes)

Bytes ----------------------------------------------------------------------------------------------

Due to time, this blog is written so much that it will be written later after the holiday

I hope the bloggers will point out my problem, and point out where I have understood the mistake, communicated with each other, and made progress together!

To be continued!

Related Article

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.