マルチキャストデリゲート
プログラミングC# p297
デリゲートに複数のメソッドを登録すると、順番に呼んでくれます。
using System; class MulticastFunctionPointer { public delegate void hello(); public static void hello_Japanese() { Console.WriteLine("こんにちは"); } public static void hello_English() { Console.WriteLine("hello"); } public static void hello_Spanish() { Console.WriteLine("HOLA!"); } static void Main(string[] args) { // 関数ポインタを定義 MulticastFunctionPointer.hello fp; fp = new MulticastFunctionPointer.hello(MulticastFunctionPointer .hello_Japanese); fp += new MulticastFunctionPointer.hello(MulticastFunctionPointe r.hello_English); fp += new MulticastFunctionPointer.hello(MulticastFunctionPointe r.hello_Spanish); fp(); } }
+=で連結しているのがミソですね。ちなみに結果はこう。
こんにちは hello HOLA!
なんだか、JavaScriptのaddEventListenerみたいな感じ。
<html> <head> <script language = "JavaScript"> function aaa() { alert("aaa"); } function bbb() { alert("bbb"); } function OnLoad() { document.form1.button1.addEventListener("click", aaa, true); document.form1.button1.addEventListener("click", bbb, true); } </script> </head> <body onLoad = "OnLoad()"> <form name = "form1"> <input type = "button" name = "button1" value = "押して"> </form> </body> </html>
ボタン押すと、関数aaaと関数bbbが両方実行されます。
このサンプルの方が、よっぽどマルチキャストデリゲートを説明してるな。。