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