C#에서 이벤트를 사용할 때 일반적인 관례는 이벤트 핸들러의 서명을 (object sender, EventArgs e) 형태로 정의하는 것이라고 한다.
여기서 sender는 이벤트를 발생시킨 객체를 참조하고, EventArgs는 이벤트와 관련된 추가정보를 포함할 수 있는 객체라고 한다.
EventArgs는 필요에 따라 확장도 가능하니 필요하면 이벤트에 관련된 데이터를 더 추가해도 된다.
EventArgs 대신 EventArgs를 상속받는 사용자 정의 이벤트를 사용해도 된다.
public class PartyEventArgs : EventArgs
{
public string Message { get; }
public PartyEventArgs(string message)
{
Message = message;
}
}
public class PartyHost
{
// EventHandler : delegate다.
public event EventHandler<PartyEventArgs> PartyStarted;
/*
* public event EventHandler<PartyEventArgs> PartyStarted;
* 이코드는 델리게이트를 따로 정의 하지 않고 C# 자체적으로 이미 정의된 EventHandler 라는 델리게이트를 사용한 것이다.
*
* EventHandler 은 아래와 같이 정의되어 있다.
* public delegate void EventHandler(object sender, EventArgs e);
*/
// 이벤트 발생시키는 메서드
public void StartParty()
{
Console.WriteLine("Party is starting!");
OnPartyStarted(new PartyEventArgs("Come join us at the party!"));
}
// 이벤트 보호 및 발생 메서드
protected virtual void OnPartyStarted(PartyEventArgs e)
{
// 이벤트가 null이 아니면 이벤트를 발생시킵니다.
PartyStarted?.Invoke(this, e);
// this 키워드를 통해 이벤트를 발생시킨 객체 전달.
}
}
public class Friend
{
// 이벤트에 응답할 메서드
public void OnPartyStarted(object sender, PartyEventArgs e)
{
Console.WriteLine($"Received an invitation from {(sender as PartyHost)?.GetType().Name}: {e.Message}");
}
}
internal class Program
{
static void Main(string[] args)
{
PartyHost host = new PartyHost();
Friend friend = new Friend();
// 이벤트 구독
host.PartyStarted += friend.OnPartyStarted;
// 이벤트 발생
host.StartParty();
}
}
EventArgs는 이벤트와 관련된 데이터를 포함할 수 있는 기본 클래스라고 한다.
EventArgs는 이벤트에 따라 추가 정보가 필요하지 않을 때 사용되며, 필요한 경우 EventArgs를 상속받아 추가 데이터를 포함하는 클래스를 정의해서 사용하면 된다고 한다.
EventHandler는 EventHandler를 제네릭 버전으로 확장한 것으로,
EventArgs 대신 사용자가 정의한 이벤트 데이터 타입을 사용할 수 있게 한다.
예제에서 사용된 EventHandler는 PartyEventArgs 타입의 이벤트 데이터를 처리할 수 있는 이벤트 핸들러를 기대한다.
EventHandler 또는 EventHandler를 사용하면 별도로 델리게이트를 정의할 필요 없이 표준화된 방법으로 이벤트를 처리할 수 있다.