I have to write class Eve to make some 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(" I have {0} ", x);
});
p.registrate (x => System.Console.WriteLine (" Square : {0} ", x * x));
p.run(10);
p.run(5);
Console.WriteLine(" Sum is {0} ", m.sum);
}
}
Output:
x = 10
I have 10
Square : 100
x = 5
I have 5
Square : 25
Sum is 20
So think I have to use delegates. And method registarte should add delegate to array of delegates.
I wrote code like this but i dint sure is wright.
public class Eve
{
int i;
public Eve()
{
i = 0;
}
public delegate void ComputeDelegate(int x);
ComputeDelegate[] delegates = new ComputeDelegate[2];
public void registrate(ComputeDelegate a)
{
if (i == 2) i = 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 I have to write method run? Or this same but in another way how i can lunch method wich is in delegate array?
Eventclass instead of just using theeventkeyword in C#?eventmight be implemented?eventkeyword. I'd like to hear from him why he can't use it.eventkeyword in C#, or by using multicast delegates and operator+/-/+=/-=, or by callingDelegate.Combine/Delegate.Removeinstead of using an array. See also this question: stackoverflow.com/questions/14197857/…