HOWTO · Csharp

C#에서 += 사용

이 문서에서는 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