A delegate is a special type of reference that encapsulates a method as a special object to pass a method as a variable or parameter
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 6 namespaceConsoleApplication17 {8 Delegate voidDualfunction (DoubleXDoubley);9 class ProgramTen { One Static voidMain () A { - dualfunction fun1; - DoubleA =2.5, B =2; theConsole.WriteLine ("Please select a function (plus 0 minus 1 by 2 except 3):"); - inti =int. Parse (Console.ReadLine ()); - if(i = =1) -FUN1 =Newdualfunction (Sub); + Else if(i = =2) -FUN1 =Newdualfunction (Mul); + Else if(i = =3) AFUN1 =Newdualfunction (DIV); at Else -FUN1 =Newdualfunction (ADD); - Fun1 (A, b); - console.readline (); - } - Static voidADD (DoubleXDoubley) in { -Console.WriteLine ("{0}+{1}={2}", x, y, x +y); to } + Static voidSub (DoubleXDoubley) - { theConsole.WriteLine ("{0}-{1}={2}", x, y, X-y); * } $ Static voidMul (DoubleXDoubley)Panax Notoginseng { -Console.WriteLine ("{0}*{1}={2}", x, y, X *y); the } + Static voidDiv (DoubleXDoubley) A { theConsole.WriteLine ("{0}/{1}={2}", x, y, X/y); + } - } $}View Code
Daulfunction fun1=new dualfunction (Sub);
Dualfunction fun1=sub;//Both of these ways.
You can also place a delegate object in an array such as
static void Main ()
{
dualfunction[] funs = new dualfunction[] {Add, Sub, Mul, Div};
Double a=2.5, b=2.0;
Console.WriteLine ("Please select function (plus 0 minus 1 by 2 except 3):");
int i = Int. Parse (Console.ReadLine ());
Funs[i] (A, b);
Console.ReadLine ();
}
A delegate object can also encapsulate the merging and deletion of multiple method delegate objects such as dualfunction fun1 = funs[1] + funs[2];
C # Delegates and methods