이벤트에 대해서 스터디한 내용을 정리.
Event를 공부하기 전, 대리자 개념을 먼저 알아야한다.
대리자는 메서드에 대한 참조를 캡슐화 하는 객체라고 한다.
=> 메서드를 나타내는 데이터 형식이다.
대리자하는 하나 이상의 메서드를 참조할 수 있으면 이를 통해 메서드를 변수처럼 전달, 할당 및 사용할 수 있다.
선언 방법은 클래스와 비슷하다.
public delegate void MyDelegate(string message);
// MyDelefate는 대리자이름, void는 반환형, string message 매개변수
반환형, 파라미터형이 일치하다면 대리자에 메서드를 할당할 수 있다.
public delegate void MyDelegate(string message);
static void Main(string[] args)
{
// 2.
// 대리자 사용 => 대리자 인스턴스 생성 및 메서드 할당
MyDelegate del = new MyDelegate(ShowMessage);
// 3.
del += ShowAnotherMessage;
// 대리자를 통한 메서드 호출
del("HI\n");
}
public static void ShowMessage(string message)
{
Console.WriteLine(message);
}
public static void ShowAnotherMessage(string message)
{
Console.WriteLine("Another message: " + message);
}
}
또한 대리자는 다중 캐스트를 지원한다.
=> 대리자 하나가 여러개의 메서드를 참조할 수 있다.
위 코드의 // 3. 부분이 ShowAnotherMessage를 대리자에 추가 한 것이다.