How to get a list of delegate call results?

Suppose I have a MulticastDelegate that implements a universal 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 is (or better I should ask why it does not exist!) A C # language function with which you can access the results of all delegate calls, that is, get a list ({8,16,32}) ?

Of course, this can be done using the .NET Framework routines. Something like this will 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 cannot understand from the system that there should be a better way, at least without casting (really, why is MulticastDelegate not universal when delegates are)?

+7
source share
3 answers

You can do what you want if you do not use Func<int> , but an Action that takes a method as a parameter that 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); } 
+3
source

No, there is no better way - when calling a multicast delegate, the result is the result of only the final delegate. This is what he likes at the level of structure.

Multicast delegates are mostly useful for event handlers. It is relatively rare to use them for such functions.

Note that Delegate itself is not generic - only individual types of delegates can be generic, as the arity of this type can vary depending on the type. (for example, Action<T> and Action<T1, T2> are indeed unrelated types.)

+6
source

It is impossible to get a) exceptions b) to return values ​​from delegates, only by sniffing into the list of results. Another way is to simply list the delegates and manage them manually.

+1
source

Source: https://habr.com/ru/post/890923/


All Articles