Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get results list of delegate's invocation?

Let say, I have a MulticastDelegate that implements generic delegate and contains several calls:

Func<int> func = null;
func += ( )=> return 8;
func += () => return 16;
func += () => return 32;

Now this code will return 32:

int x = func(); // x=32

I would like to know if there exists (or better I should ask why it doesn't exist!) the C# language feature using which is possible to get the access to results of all delegate's invocations, that means to get the list ({8,16,32})?

Of course it's possible to do the same using .NET framework routines. Something like this will do the work:

public static List<TOut> InvokeToList<TOut>(this Func<TOut> func)
{
    var returnValue = new List<TOut>();
    if (func != null)
    {
        var invocations = func.GetInvocationList();
        returnValue.AddRange(invocations.Select(@delegate => ((Func<TOut>) @delegate)()));
    }
    return returnValue;
}

But I can't get out from the system that there should be the better way, at least without casting (really, why MulticastDelegate is not generic when delegates are)?

like image 295
Roman Pokrovskij Avatar asked Jun 20 '11 12:06

Roman Pokrovskij


1 Answers

No, there isn't a better way - when you invoke a multicast delegate, the result is just the result of the final delegate. That's what it's like at the framework level.

Multicast delegates are mostly useful for event handlers. It's relatively rare to use them for functions like this.

Note that Delegate itself isn't generic either - only individual delegate types can be generic, because the arity of the type can change based on the type. (e.g. Action<T> and Action<T1, T2> are unrelated types really.)

like image 134
Jon Skeet Avatar answered Sep 23 '22 13:09

Jon Skeet