包含多個方法的委托成為多播委托,調用多播委托,可以按照順序連續調用多個方法,因此,委托的簽名就必須返回void;
否則,就只能得到委托調用的最好一個方法的結果
1、多播委托可以用運算符"+"和"+="給委托添加方法調用,同樣也可以用運算符"-"和"-="給委托刪除方法調用
void Hello(string s) { System.Console.WriteLine(" Hello, {0}!", s); } static void Goodbye(string s) { System.Console.WriteLine(" Goodbye, {0}!", s); throw new Exception("error"); } Action<string> ac=Hello; ac+=Goodbye;
2、多播委托包含一個逐個調用委托集合,如果通過委托嗲用的其中一個方法拋出一個異常,整個迭代就會停止;、
為了避免這個問題,應該自己迭代方法列表。Delegate類定義GetInvocationList()方法,他返回一個Delegate
對象數組
void Hello() { } static void Goodbye() { } Action ac=Hello; ac+=Goodbye; Delegate[] delegates=ac.GetInvocationList(); foreach(Action action in delegates) { try { action(); }catch(Exception) { } }