c# - How make arrays of delegates and use this array? -
i have write class eve make code below:
class mainclass { int sum = 5; public void add (int x) { sum += x; } public static void write (int x) { console.writeline("x = " + x); } public static void main (string[] args) { eve p = new eve(); mainclass m = new mainclass(); p.registrate(m.add); p.registrate(write); p.registrate (delegate (int x) { system.console.writeline(" have {0} ", x); }); p.registrate (x => system.console.writeline (" square : {0} ", x * x)); p.run(10); p.run(5); console.writeline(" sum {0} ", m.sum); } }
output:
x = 10
i have 10
square : 100
x = 5
i have 5
square : 25
sum 20
so think have use delegates. , method registarte should add delegate array of delegates.
i wrote code dint sure wright.
public class eve { int i; public eve() { = 0; } public delegate void computedelegate(int x); computedelegate[] delegates = new computedelegate[2]; public void registrate(computedelegate a) { if (i == 2) = 0; delegates[i] += a; i++; } public void run() { //delegates[0].; } } public class mainclass { int sum = 5; public void add(int x) { sum += x; } public void write(int x) { console.writeline("x = " + x); } static void main() { eve proc1 = new eve(); mainclass m = new mainclass(); proc1.registrate(m.add); proc1.registrate(m.write); } } }
i have problem how have write method run? or same in way how can lunch method wich in delegate array?
it looks need delegates[0](x);
x
int
want pass 0
th entry in array.
(delegates
has type computedelegate[]
. computedelegate
type has same signature , return type system.action<int>
, of course.)
Comments
Post a Comment