c# - Delegate using different methods of different classes -
using system; delegate int numberchanger(int n); namespace delegateappl { class testdelegate { static int num = 10; public static int addnum(int p) { num += p; return num; } public static int multnum(int q) { num *= q; return num; } public static int getnum() { return num; } static void main(string[] args) { //create delegate instances numberchanger nc1 = new numberchanger(addnum); numberchanger nc2 = new numberchanger(multnum); //calling methods using delegate objects nc1(25); console.writeline("value of num: {0}", getnum()); nc2(5); console.writeline("value of num: {0}", getnum()); console.readkey(); } }
in above code function called , calling function in same class.... can use both in seperate classes?
if possible please give example ......
surely can.
just put methods in separate class , create instance of access them:
class arithmetic { int num = 10; public int addnum(int p) { num += p; return num; } public int multnum(int q) { num *= q; return num; } }
now call methods:
class testdelegate { public delegate int numberchanger(int n); static void main(string[] args) { //create instance of class arithmetic art = new arithmetic(); //create delegate instances numberchanger nc1 = new numberchanger(art.addnum); //call reference numberchanger nc2 = new numberchanger(art.multnum); //call reference //calling methods using delegate objects //add console.writeline("value of num: {0}", nc1(25)); //use directly because delegate returns value //product console.writeline("value of num: {0}", nc2(5)); //use directly because delegate returns value console.readkey(); } }
note: don't need getnum()
method returning value every method , delegate returns well. have removed static
everywhere because seems need it.
Comments
Post a Comment