C # Delegate Origin
In recent internships and career fairs, I have been asked a lot of technical questions, and C # asks more about delegates and LINQ. LINQ has written an article before, and you can see
http://blog.csdn.net/yzysj123/article/details/38778371.
Here's why C # uses delegates and what is a delegate. Learn C + + know, C + + pointers are very flexible and easy to use, but also to programmers have brought a lot of headaches, such as the wild pointer problems. and C # abandoned the pointer, but the corresponding function through the other way to practice, such as C + + pointer variables, references, C # inside can be achieved through ref,out and so on. C + + pointer functions, C # can be implemented by a delegate, see the following example.
#include <string.h> #include <stdio.h> int funca (int a,int b); int FUNCB (int a,int b); int Main (int argc, char *argv[]) { int (*func) (int,int); func = Funca; printf ("%d\n", Func (10,1)); func = FUNCB; printf ("%d\n", Func (10,1)); } int Funca (int a,int b) { return a + b; } int FUNCB (int a,int b) {return a-a ;}
The above is a pointer function through C + + to call a number of other functions of the same parameter type. The functionality delegated in C # can also be seen as an implementation of the functionality of C + +. The specific code is as follows:
<span style= "Color:rgb (0, 130, 0); Font-family:consolas, ' bitstream Vera Sans Mono ', ' Courier New ', Courier, monospace; line-height:21.59375px; White-space:pre-wrap; " >//excerpt from "</span><span style=" Color:rgb (0, 130, 0); Font-family:consolas, ' bitstream Vera Sans Mono ', ' Courier New ', Courier, monospace; line-height:21.59375px; White-space:pre-wrap; " >c# Introduction Classic "</SPAN>
Using system;using system.collections.generic;using system.linq;using system.text; Namespace weituo{class Program {static void Main (string[] args) {//DECLARE delegate variable Pr Ocessdelegate process; Console.WriteLine ("Please enter two numbers separated by commas:"); string input = Console.ReadLine (); int commapos = input. IndexOf (', '); Double param1 = convert.todouble (input. Substring (0, Commapos)); Double param2 = convert.todouble (input. Substring (Commapos + 1,input. LENGTH-COMMAPOS-1)); Console.WriteLine ("Input m multiplication D Division </a>"); Input =console.readline (); Initialize the delegate variable if (input = = "M") process = new Processdelegate (Multiply); Note: The process = Multiply else process = new Processdelegate (Divide) can also be written here; Use a delegate to invoke a function double result = Process (PARAM1,PARAM2); Console.WriteLine ("Result: {0}", result); Console.rEadkey (); }//Declaration delegate delegate Double Processdelegate (double param1,double param2); Static double Multiply (double param1, double param2) {return param1 * PARAM2; } static double Divide (double param1, double param2) {return param1/param2; } }}
Humble opinion of C # Delegation