我需要更多地了解委托和C#语言设计.
比方说,我有一个MulticastDelegate实现泛型委托并包含几个调用:
Func<int> func = null;
func += ( )=> return 8;
func += () => return 16;
func += () => return 32;
Run Code Online (Sandbox Code Playgroud)
现在这段代码将返回32:
int x = func(); // x=32
Run Code Online (Sandbox Code Playgroud)
我想知道是否存在(或者更好,我应该问为什么它不存在!)使用C#语言特性可以访问所有委托调用的结果,这意味着获取列表({8 ,16,32})?
当然,使用.NET框架例程也可以这样做.这样的事情会做的工作:
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;
}
Run Code Online (Sandbox Code Playgroud)
但我无法从系统中得出应该有更好的方法,至少没有强制转换(真的,为什么MulticastDelegate在代理时不通用)?