반응형
이벤트(Event)란?
C#에서 모든 이벤트(event)는 특수한 형태의 delegate이다.
이벤트는 특수한 제약조건이 추가된 delegate라고 생각하면 이해하기 편하다.
- 이벤트의 추가(+=) 및 제거(-=)만 가능하다. 할당이 불가능하다.(= 으로 이벤트 할당 불가)
- 클래스 외부에서 직접 이벤트를 호출할 수 없다.
namespace System
{
//
// 요약:
// Represents the method that will handle an event that has no event data.
//
// 매개 변수:
// sender:
// The source of the event.
//
// e:
// An object that contains no event data.
public delegate void EventHandler(object? sender, EventArgs e);
}
미리 정의되어 있는 EventHandler 라는 이름의 delegate
이벤트 발생시에 함수를 실행시키려면 해당 형식을 맞춰서 함수를 선언해서 등록해줘야 한다.
예제 코드
class Program
{
static void Main(string[] args)
{
var button = new MyButton();
// 3. eventhandler에 이벤트 추가
button.Click += new EventHandler(BtnClick);
// 4. 이벤트 발생을 위한 함수 호출
button.MouseButtonDown();
}
// 2. eventhandler에 추가할 형식에 맞는 event 함수 선언
static void BtnClick(object sender, EventArgs e)
{
Console.WriteLine("button clicked!");
}
}
public class MyButton
{
// 1. event 선언
public event EventHandler Click;
public void MouseButtonDown()
{
if (this.Click != null)
{
// 5. 이벤트 발생
Click(this, EventArgs.Empty);
}
}
}
천천히 주석을 따라가면서 event에 대해서 이해해 보도록 하자.
예제 코드에 Effective C# item 8의 내용을 적용한 코드
public class MyButton
{
// 1. event 선언
public event EventHandler Click;
public void MouseButtonDown()
{
// 5. 이벤트 발생
Click?.Invoke(this, EventArgs.Empty);
}
}
함께 읽으면 좋은 글
Effective C# Item 8 : 이벤트 호출 시에는 null 조건 연산자를 사용하라.
이벤트 호출 시에는 null 조건 연산자를 사용하라 이벤트를 발생시키는 작업은 간단해 보인다. 이벤트를 정의하고, 이벤트를 발생시켜야 할 경우 이벤트를 호출하기만 하면 이벤트에 결합되어
jettstream.tistory.com
C# 대리자, 델리게이트(Delegate)에 대해서
대리자(Delegate)란? 특정 매개 변수 목록과 반환 형식이 있는 매서드에 대한 참조를 나타내는 형식입니다. 대리자를 인스턴스화할 때 호환되는 매개변수 및 반환 형식을 가지는 모든 메서드와 연
jettstream.tistory.com
'프로그래밍 > C#' 카테고리의 다른 글
C# 스레드(Thread)에 대해서 (10) | 2023.04.19 |
---|---|
C# is, as, typeof(), GetType() Type-testing 연산자에 대해서 (8) | 2023.04.12 |
C# Ref 와 Out 키워드 차이점에 대해서 (0) | 2023.04.04 |
C# 확장 메서드(Extension Method) (2) | 2023.04.03 |
Boxing, UnBoxing에 대해서 알아보자 (1) | 2023.03.31 |
댓글