[英]Executing multicast delegates
我有多個目標
Func<int,int,int> funHandler=Max;
funHandler+=square;
當我執行Console.WriteLine(funHandler(10,10));
它返回square
的10(即)200.It不火Max
。
我用過類似的東西
foreach(var v in funHandler.GetInvocationList())
{
Console.WriteLine(v(10,20));
}
'V'是一個變量,但其用法類似於方法。我該如何激發委托調用列表中的所有方法?
恩, Max
可能沒有副作用嗎?您不會注意到嗎? 當您執行多播委托時,它僅返回最后一個委托的結果。
嘗試這個:
Func<int, int, int> funHandler = (x, y) => { Console.WriteLine(x); return x; };
funHandler += (x, y) => { Console.WriteLine(y); return y; };
int res = funHandler(1, 2);
Console.WriteLine(res);
看到? 有用
要使用調用列表,請執行以下操作:
foreach (var v in funHandler.GetInvocationList())
{
((Func<int, int, int>)v)(1, 2);
}
要么:
foreach (Func<int, int, int> v in funHandler.GetInvocationList())
{
v(1, 2);
}
多播與返回一些東西的委托對我來說沒有多大意義。 我猜它會執行所有這些操作,但會丟棄所有結果,只有一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.