C# での+=の使用

Haider Ali 2023年10月12日
C# での+=の使用

このガイドでは、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
著者: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

関連記事 - Csharp Operator