.NET Visual C#言語入門 > デリゲートサンプル
のぶ亭『プログラミングの相談窓口』 … 様々なプログラミング問題を個別対応致します |
デリゲートサンプル
デリゲート&イベント発生と受信のサンプル
イベントとは、関連するオブジェクトで、重要な事象が発生したとき、非同期で通知すること。
クラスを提供する際、何らかの重要な事象が発生したとき、イベントを発行して通知する必要がある場合があります。そのための、イベント発生側クラスとイベント受信側クラスの関係を最小限のコードで解説します。
Main |
public class AlarmDriver { public static void Main(string[] args) { Recv a = new Recv(); ① } }
|
イベント受信側クラス |
public class Recv { Send s; public Recv() { s = new Send(); ① s.Alarm += new QuitEventHandler(this.Quit); ② s.EventQUIT(); ③ } public void Quit(object sender) ④ { Console.WriteLine("QUIT"); } }
|
イベント発行側クラス |
public delegate void QuitEventHandler(object sender); ① public class Send { public event QuitEventHandler Alarm; ② public void EventQUIT() ③ { Alarm(this); } }
|