Reputation: 125
I have very simple delegate:
public delegate int Compute(int i, int j);
and some functions:
static int sum(int x, int y)
{
return x + y;
}
static int diff(int x, int y)
{
return x - y;
}
static int times(int x, int y)
{
return x * y;
}
Then I am declaring an event as:
public static event Compute e;
In main I am adding functions to event:
e += new Compute(sum);
e += new Compute(diff);
e += new Compute(times);
And finally I would like write all results of function, so:
Console.WriteLine(e.Invoke(3,4));
As I understood Invoke
method is invoking all function in event. But in my case I see the result only of the last added function - so 12
. How can I get all results of Invoke
method ?
If functions aren't returning any type (they are void type) there is no problem, but if functions are returning something - there is.
Upvotes: 1
Views: 217
Reputation: 1503599
You have to call MulticastDelegate.GetInvocationList
, which will allow you to invoke one handler at a time:
// TODO: Don't call your event e, and use Func<int, int, int>
foreach (Compute compute in e.GetInvocationList())
{
int result = compute(3, 4);
Console.WriteLine("{0} returned {1}", compute.Method.Name, result);
}
Upvotes: 5
Reputation: 33391
It is by design. If you want to get all results you must get the list of delegates using GetInvokationList() method and then iterated by list and call all delegates.
Upvotes: 0