简体   繁体   中英

Executing multicast delegates

I have a Multiple target

Func<int,int,int> funHandler=Max;
funHandler+=square;

When i execute Console.WriteLine(funHandler(10,10)); it return the square of 10 (ie) 200.It did not fire Max .

i used something like

foreach(var v in funHandler.GetInvocationList())
{
    Console.WriteLine(v(10,20));
}

'V' is a variable,but it is used like a method.How can i fire all methods that is in delegate's invocation list?

Well, may be Max has no side effects and you can't notice it? When you execute multicast delegate it returns result of only last delegate.

Try this:

Func<int, int, int> funHandler = (x, y) => { Console.WriteLine(x); return x; };
funHandler += (x, y) => { Console.WriteLine(y); return y; };
int res = funHandler(1, 2);
Console.WriteLine(res);

See? it works

To use invocation list do this:

foreach (var v in funHandler.GetInvocationList())
{
    ((Func<int, int, int>)v)(1, 2);
}

Or:

foreach (Func<int, int, int> v in funHandler.GetInvocationList())
{
    v(1, 2);
}

Multicast with a delegate that returns something doesn't make much sense to me. I'd guess it executes all of them but discards all results but one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM