usingSystem;using StaticSystem.Console;//Delegate Reduction coupling//if the argument of a function is a function//You can define a delegatenamespaceconsoleapp{classProgram {//Delegate//delegates can be defined inside, outside, and namespace of a class//equivalent to a function type Public Delegate voidWtiteastring (inti); Public Static voidFuninti) {WriteLine (i); } Public Static voidfun1 () {}Static voidMain (string[] args) { //replication will reassign a methodWtiteastring Write =Fun ; Write=Newwtiteastring (fun); Write (1); //action<t> delegate, return type voidaction<int> OP1 =Fun ; OP1 (2); Action D=fun1; //func<t> Delegate//A single parameter that represents the return type, a parameter that precedes the method, and the last represents the return typefunc<int,Double>OP2; //Multicast delegates, using + + =-=//The order of their calls is not formally defined, so avoid writing code that relies on sequential invocation of methodsOP1 + =Fun ; //if a delegate invokes a method that throws an exception, the delegate iteration stops, and no other method is called//to avoid this situation, you should iterate through the list of methods yourselfAction D1 =fun1; D1+=fun1; Delegate[] Delegates=D1. Getinvocationlist (); foreach(Action D2inchdelegates) { Try{D2 (); } Catch(Exception) {WriteLine ("Exception caught"); } } //Anonymous method delegate an existing write function//Anonymous methods cannot use a jump statement (break goto continue) to jump outside the anonymous method//external ref, out parameters cannot be accessed, but other external variables can be used stringMID =", middle part,"; Func<string,string> Anondel =Delegate(stringparam) {param+=mid; Param+="And this is added to the string."; returnparam; }; WriteLine (Anondel ("start of String")); //lambda expressionfunc<string,string> Oneparam =S2= = $"Change Uppercase {s2. ToUpper ()}";//s2 as parameterWriteLine (Oneparam ("Test")); //Multiple Parametersfunc<Double,Double,Double> twoparams =(x, y)= x *y; WriteLine (Twoparams (2,3)); } }}
C # Delegate