HOWTO · Csharp
C# での+=の使用
この記事では、C# での plus equals+=演算子の使用について説明します。
このガイドでは、C# の+= 演算子について学習します。C# の+= は、他のプログラミング言語とは異なります。
他のすべての言語と同様に、代入演算子としても使用できます。C# での他の用途を見ていきます。
飛び込みましょう。
C# の EventHandler として+= を使用する
C# 言語では、演算子+= は、イベントに応答して呼び出されることになっているメソッドを指定します。
これらのタイプのメソッドは、イベントハンドラーとも呼ばれます。EventHandler は、組み込みメソッドを備えた C# のクラスです。
以下のコードでは、カスタムイベントハンドラークラスを作成しました。見てください。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OpreationEvents {
class MyEvents {
public event EventHandler ApplicationEvent // Builtin Methods
{
add // writing custom event handler class.
{
Console.WriteLine("Add operation EVENT");
}
remove {
Console.WriteLine("Remove operation EVENT");
}
}
static void Main() {
MyEvents temp = new MyEvents();
temp.ApplicationEvent += new EventHandler(temp.Trigger); // Assging method to event;
temp.ApplicationEvent -= null; // Removing Event Methods
Console.Read();
}
void Trigger(object sender, EventArgs e) {
Console.WriteLine("I will Trigger on Event Happening");
}
}
}
上記のコードでは、void メソッド trigger() がイベントに割り当てられています。そのイベントが発生するたびに、trigger() 関数がトリガーされます。
-= 演算子を使用して、操作イベントを削除することもできます。これは、+= 演算子で学んだことの反対です。
出力:
Add operation EVENT
Remove operation EVENT