1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# イベントハンドラ登録の書きかた変遷

Last updated at Posted at 2019-11-01

いまさらだけども。

書き方#1

以前はこんな感じで書いていた(気がする)。

イベントハンドラの追加処理

class クラス
{
    メソッド
    {
        
        button1.Click += new EventHandler(button1_Click);
        
    }
}
イベントハンドラのメソッド記載

void button1_Click(object sender, EventArgs e)
{
    
}

書き方#2

new EventHandlerは省略できて、下記のように書ける。

イベントハンドラの追加処理

class クラス
{
    メソッド
    {
        
        button1.Click += button1_Click;
        
    }
}
イベントハンドラのメソッド記載

void button1_Click(object sender, EventArgs e)
{
    
}

書き方#3

ラムダ式で匿名メソッドとして書ける。かなり短くなった。
「処理内容」は、1行で書けないならメソッド化したほうが見やすい気がする。

イベントハンドラの追加処理

class クラス
{
    メソッド
    {
        
        button1.Click += (sender,e)=>{ 処理内容 };
        
    }
}

使いわけ

EventArgs(もしくはその派生クラス)の引数を使いたいときは書き方#2を使いたくなるところ。
同じ.csファイル内では、書き方#2か書き方#3で統一したい。

参考サイト

https://www.ipentec.com/document/csharp-add-event-handler-by-code
https://tnakamura.hatenablog.com/entry/20090309/1236549534

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?