In this section of code i'll demonstrate how to call many methods at runtime associated with that particular delegate.
using System; using System.Collections.Generic; using System.Text;
namespace DelegatesHandling { public delegate decimal Calculator(decimal num1, decimal num2); public delegate void Test(string str);
class Program { Calculator claci_1; Calculator claci_2; Calculator calci;
decimal Addition(decimal n1,decimal n2) { return n1 + n2; } decimal Subtraction(decimal n1, decimal n2) { return n1 - n2; }
void TestMethod1(string str) { Console.WriteLine("I am in TestMethod1 "+str); } void TestMethod2(string str) { Console.WriteLine("I am in TestMethod2 " + str); }
static void Main(string[] args) {
Program pgm = new Program(); pgm.claci_1 = new Calculator(pgm.Addition); pgm.claci_2 = new Calculator(pgm.Subtraction);
pgm.calci = new Calculator(pgm.Subtraction); pgm.calci += new Calculator(pgm.Addition); decimal result = pgm.claci_1(12.23m, 344.422m); Console.WriteLine("Addition = "+result);
result = pgm.claci_2(12.23m, 344.422m); Console.WriteLine("Subtraction = " + result);
result = pgm.calci(12.2m,13.8m); Console.WriteLine("Subtraction = " + result);
Console.ReadLine();
} } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|