简体   繁体   中英

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)?

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. (eg Action<T> and Action<T1, T2> are unrelated types really.)

You can accomplish what you want if you don't use a Func<int> , but an Action which takes a method as parameter which processes the return values. Here is a small example:

    static Action<Action<int>> OnMyEvent=null;

    static void Main(string[] args)
    {
        OnMyEvent += processResult => processResult(8);
        OnMyEvent += processResult => processResult(16);
        OnMyEvent += processResult => processResult(32);

        var results = new List<int>();
        OnMyEvent(val => results.Add(val));

        foreach (var v in results)
            Console.WriteLine(v);

    }

There is no way to get a) exceptions b) return values from delegates, only by sniffing into result list. Another way is just to have list of delegates and manage it manually.

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