■ はじめに
https://dk521123.hatenablog.com/entry/2010/12/12/164101
の続き。 今度は、Event (イベント)について、取り上げる。
■ イベント
* あるクラスで発生したイベントを、他のクラスに伝えるために使用
■ 利用手順
1)デリゲートの定義 2)イベントの宣言 3)イベントの登録 4)イベントの発生
1)デリゲートの定義
* イベントに使うメソッドの引数と戻り値をつけたら、 delegate キーワードを頭につけて、デリゲートの定義を行う * 一般的に、第一引数にイベントを発生させるクラス、 第二引数にイベントに関する情報を渡す
サンプル
delegate void SampleDelegate(object sender, EventArgs e);
2)イベントの宣言
* public event キーワードを利用し、 デリゲートへの参照を保持するフィールドを定義する
サンプル
public event SampleDelegate SampleEvent;
3)イベントの登録
* イベントの登録は、+=演算子を使用してイベントフィールドに設定する
サンプル
sampleObject.SampleEvent += anotherObject.SampleHandler;
4)イベントの発生
* イベントを発生させる場合は、イベントフィールドに対して引数を渡して呼び出す * 呼び出し時に、事前にイベントフィールドがnullでないことを確認する必要がある
サンプル
if (SampleEvent != null) { EventArgs e = new EventArgs(); SampleEvent(this, e); }
■ サンプル
* イベントハンドラ => さまざまなイベントが発生した際に処理されたメソッド
SampleEvent.cs
// イベントを持つクラス using System; namespace Test { public class Sample { // [1] デリゲートの定義 public delegate int SampleDelegate(object instance, EventArgs eventArgs); // [2] イベントの宣言 public event SampleDelegate SampleEvent; public int Execute(int arg) { // [4] イベントの発生 if (SampleEvent != null) { int value = SampleEvent(this, new EventArgs()); return arg * value; } } } }
Form1.cs
// イベントを呼び出すメソッド private void button1_Click(object sender, EventArgs e) { Sample sampleObject = new Sample(); // [3] イベントの登録 // メソッドをイベントハンドラに登録(デリゲートのインスタンスをイベントに追加) sampleObject.SampleEvent += Method100; int result = sampleObject.Execute(10); // メソッドを実行 this.label1.Text = "Result = " + result; // 出力 sampleObject.SampleEvent -= Method100; sampleObject.SampleEvent += Method200; // メソッドをイベントハンドラに登録 result = sampleObject.Execute(10); // メソッドを実行 this.label2.Text = "Result = " + result; // 出力 } public static int Method100(object instance, EventArgs eventArgs) { Console.WriteLine("Method100を実行"); return 100; } public static int Method200(object instance, EventArgs eventArgs) { Console.WriteLine("Method200を実行"); return 200; }
参考資料
http://www.atmarkit.co.jp/fdotnet/csharp_abc/csharp_abc_017/csharp_abc01.html
■ イベントの引数について
System.EventArgs クラス
* イベントに関する情報を保持
参考資料
http://www.yo.rim.or.jp/~nag/cgi-bin/wiki.cgi?p=Visual+Studio.NET
■ メモ
* イベントをイベント ハンドラに関連付けるには... =>『デリゲートのインスタンスをイベントに追加』する。 ★まだしっくり感覚的に分かっていない * デリゲートを削除しない限り、そのイベントが発生すると、 常にイベント ハンドラが呼び出される
関連記事
Delegate / Event ~ 入門編 / Delegate ~
https://dk521123.hatenablog.com/entry/2010/12/12/164101
Delegate / Event ~ 基本編 ~
https://dk521123.hatenablog.com/entry/2010/10/22/101350
Delegate / Event ~ イベント・画面と処理の分離 ~
https://dk521123.hatenablog.com/entry/2011/02/19/154156
Delegate / Event ~ 非同期デリゲート・バックグラウンド処理を行う ~
https://dk521123.hatenablog.com/entry/2013/05/27/214444
Delegate / Event ~ 非同期デリゲート・コールバック関数を実装する ~
https://dk521123.hatenablog.com/entry/2019/03/09/175924
Delegate / Event ~ Action デリゲート ~
https://dk521123.hatenablog.com/entry/2011/04/04/224133
Delegate / Event ~ Func デリゲート ~
https://dk521123.hatenablog.com/entry/2014/05/28/234856