Calling delegate with multiple functions having return values

前端 未结 3 1196
渐次进展
渐次进展 2021-01-04 22:18

I am trying to understand concept of delegates and have got a query. Suppose that we have a delegate defined with return type as int and accepting in 2 parameters of type in

相关标签:
3条回答
  • 2021-01-04 23:04

    Actually, with a little bit of trickery and casting, you can get all of the results like this:

    var b = new BinaryOp(Add);
    b += new BinaryOp(Multiply);
    
    var results = b.GetInvocationList().Select(x => (int)x.DynamicInvoke(2, 3));
    foreach (var result in results)
        Console.WriteLine(result);
    

    With output:

    5
    6
    
    0 讨论(0)
  • 2021-01-04 23:10

    You will get the return value of the last method added to the multicast delegate. In this case, you will get the return value of Multiply.

    See the documentation for more on this: https://msdn.microsoft.com/en-us/library/ms173172.aspx

    0 讨论(0)
  • 2021-01-04 23:10

    Yes, invoking a multicast delegate calls all subscribed methods, but no, an array of results is not returned - only the result returned by the last subscriber is returned.

    To obtain the returned results of all subscribers, what you could do instead is to build a collection of typed Funcs which you can then invoke and collate the results:

     IEnumerable<int> InvokeResults(IEnumerable<Func<int, int, int>> operations, 
                                    int x, int y)
     {
         return operations.Select(op => op(x, y));
     }
    

    And invoke like such:

     var results = InvokeResults(new Func<int, int, int>[] {Add, Multiply}, 2, 3);
    
    0 讨论(0)
提交回复
热议问题