Preface:
Delegate in C# is similar to pointers to functions in C or C++. A delegate is a reference type variable that contains a reference to a method. References can be changed at runtime. Delegate is especially used to implement event and callback methods. All delegations are derived from classes. Pass a method as a parameter and let other methods be called and executed.
1. Declaration of delegation
The delegation statement determines the methods that can be cited by the delegation. The delegate can point to a method with the same label as it.
1.
1.1.1. 0-23 parameters, there can be a return value or no return value
public delegate int MyDelegateEventHandler (string parm);
Note: (1). The method pointed to by this delegate must be of the parameter of type string and the return type is of type int. Other statements compare the proceeds.
(2).EventHandler is a c# naming specification. Of course, I understand that the specification is free.
(3). When delegate calls, you must determine whether it is null or an exception will be reported.
(4). Events are also a kind of commission
1.1.2. Delegated call
MyDelegateEventHandler fun=new MyDelegateEventHandler(method); or MyDelegateEventHandler fun=method; // Fun is not empty, then callback method if (fun!= null) { fun(val); } //fun?.Invoke(val); Simplified version calls
1.1.3. Delegated multicast
Each delegate contains only one method call. If multiple methods are called, it is necessary to display the call to this delegate multiple times. If multiple methods are called by the same delegate, we can use multicast delegate
public delegate void MyDelegate (); public voidMyMethod() { //# } public void MyMethod1() { //# } public void MyMethod2() { //# } MyDelegateEnventHander myDelegate; myDelegate=new MyDelegateEventHander(MyMethod); myDelegate+=new MyDelegateEventHander(MyMethod1); ........... //CallmyDelegate();
Note:
1. The delegate objects can be merged using the "+" operator;
2. The "-" operator can be used to remove component delegates from merged delegates;
3. The delegate specified method types must be consistent;
4. The return type is generally void, but not required;
Get the delegate index
if (MyDelegate != null) [] dels = MyDelegate .GetInvocationList(); for (int i = 0; i < ; i++) { MyDelegate -= dels[i] as MethodDelegate; }
The above is a simple application to obtain delegate indexes using GetInvocationList.
1.
Action has at least 0 parameters, up to 16 parameters, no return value.
Action Indicates no parameters,Delegate without return value Action<int,string> Indicates that there are incoming parametersint,stringDelegate without return value Action<int,string,bool> Indicates that there are incoming parametersint,string,boolDelegate without return value Action<int,int,int,int> Indicates that there is incoming4indivualintType parameters,Delegate without return value
public void Test<T>(Action<T> action,T p) { action(p); }
1.
Func has at least 0 parameters, up to 16 parameters, returned according to the return value. Must have a return value, not void
Funcis a generic delegate without return value Func<int> Indicates no parameters,The return value isintCommission Func<object,string,int> Indicates that the incoming parameter isobject, string The return value isintCommission Func<object,string,int> Indicates that the incoming parameter isobject, string The return value isintCommission Func<T1,T2,,T3,int> Indicates that the incoming parameter isT1,T2,,T3(Generics)The return value isintCommission
1.
is a generic delegate that returns a bool type;
<int> means that the incoming parameter is int and returns the delegate of bool;
There is and only one parameter, and the return value is fixed to bool;
public delegate bool Predicate<T> (T obj)
2. Instantiation of delegates
2.
public delegate int MyDelegateEventHandler (string parm) public int MyMethod(string parm) { //# } MyDelegateEventHandler MyDelegate=new MyDelegateEventHandler(MyMethod)
Note: When delegate is instantiated, delegate objects must be created using the new keyword and are related to a specific method. The methods in the delegate parameters do not contain parameters.
2. Use
public void Test<T>(Action<T> action, T p) { action(p); } private void Action(string s) { # } //CallTest<string>(Action,"wyl");
2. Use
public int Test<T1, T2>(Func<T1, T2, int> func, T1 a, T2 b) { return func(a, b); } private int Fun(int a, int b) { # } //CallTest<int,int>(Fun,100,200)
2.4 Entrusting to implement bubble sorting
//Define the objectclass Student { public string Name { get; private set; } public decimal Scores{ get; private set; } public Student(string name, decimal scores) { = name; = scores; } public override string ToString() { return ("{0},{1:C}",Name,Scores); } public static bool CompareScores(Student e1,Student e2) { return < ; } } //Use commission to achieve bubbleclass BubbleScores { public static void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison) { bool swapped = true; do { swapped = false; for (int i = 0; i < - 1; i++) { if (comparison(sortArray[i + 1], sortArray[i])) { T temp = sortArray[i]; sortArray[i] = sortArray[i + 1]; sortArray[i + 1] = temp; swapped = true; } } } while (swapped); } } //CallStudent[] students={new Student("wyl", 100),#}; (students, ); foreach(var student in students) (student);
3. Anonymous functions and lambda
3.1 What is anonymous function
Anonymous functions are "inline" statements or expressions that can be used anywhere a delegate type is required.
An anonymous function can be used to initialize a named delegate (no named delegate required), or to pass a named delegate (rather than a named delegate type, passing a method block instead of a delegate type) [callback way] as a method parameter.
MyDelegate funDelegate = delegate(string s) { (s); }; funDelegate ("this is anonymous delegate");
3.
The lambda expression is actually an anonymous function. After the compiler sees the lambda, it will automatically define a new private method in the class. The lambda must match the delegate! Among them, lambda is referenced from c# 3.0
The syntax of lambda:
Parameters => Method body.
=>The left is the parameter to be passed in, in this example, a variable of type Int is passed, and =>The right is the specific code.
//If the parameters are not passed:()=>("Hello World!") //Pass a parameter:(int n)=>(()) //Or remove() and int compiler will infer the type by itself:n=>(()) //Pass multiple parameters:(int n ,int m)=>(n+m) // Or the compiler itself infers the type:(n , m)=>(m+n)
4. To sum up:
1. Delegate is similar to C++ function pointers.
2. Delegate allows methods to be passed as parameters.
3. Delegation can be used to define callback methods.
4. Delegations can be linked together; multicast.
5. The method does not have to exactly match the delegate signature.
The above is the basic knowledge of c# ----delegation, anonymous functions, and lambda. For more information about c# delegation, anonymous functions, and lambda, please follow my other related articles!