Skip to content

Instantly share code, notes, and snippets.

@taktamur
Last active August 29, 2015 14:05
Show Gist options
  • Save taktamur/6f68ccf22df2334b0c66 to your computer and use it in GitHub Desktop.
Save taktamur/6f68ccf22df2334b0c66 to your computer and use it in GitHub Desktop.
Xamarinで遊ぶ(4) eventを試す ref: http://qiita.com/paming/items/7317ea756a250143912e
class MainClass
{
public class Hoge
{
// Actionの他に EventHandler<object o, EventArgs e> がある。
public event Action<string> ActionHandler;
// Actionは、 Action Action<T> Action<T1,T2> 〜 Action<T1...T16>まである。
// http://msdn.microsoft.com/ja-jp/library/system.action(v=vs.110).aspx
public void DoAction ()
{
if (this.ActionHandler != null) {
// 1回の呼び出しに見えるが、実際には登録されたイベント全てが呼ばれる
this.ActionHandler (@"call action.");
}
}
}
public static void Main (string[] args)
{
// ↓を参考にいろいろなイベント登録を試す
// http://www.atmarkit.co.jp/fdotnet/rapidmaster/rapidmaster_01/rapidmaster_01.html
//
Hoge hoge = new Hoge ();
// Action<string> へのいろいろなイベント追加方法
hoge.ActionHandler += m => Console.WriteLine (" event1 message=" + m);
hoge.ActionHandler += (m) =>{
Console.WriteLine (" event2 message=" + m);
};
hoge.ActionHandler += delegate(string m){
Console.WriteLine (" event3 message=" + m);
};
hoge.ActionHandler += ActionHandlr4;
hoge.DoAction ();
Console.WriteLine ();
// イベントの削除
hoge.ActionHandler -= ActionHandlr4; // これは削除出来る
// ラムダ式を指定いてもイベントは削除出来ない。同一かどうか判断つかないから当然
hoge.ActionHandler -= m => Console.WriteLine (" event1 message=" + m); // これは削除出来ない
hoge.DoAction ();
// クラスの外側から、eventを呼び出す事は出来ない
// ↓はコンパイルエラーになる。
// hoge.ActionHandlr ("hoge");
// ↓取り出す事も出来ない(コンパイルエラー)
// var actions = hoge.ActionHandler;
}
public static void ActionHandlr4(string m){
Console.WriteLine (" event4 message=" + m);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment