다른 클래스에 정의된 이벤트를 사용하려면 이벤트 처리기를 정의하고 등록해야 합니다. 이러한 이벤트 처리기는 이벤트에 대해 선언된 대리자와 메서드 시그니처가 같아야 합니다. 이벤트에 처리기를 추가하여 이벤트 처리기를 등록할 수 있습니다. 이벤트에 이벤트 처리기를 추가하고 나면 클래스에서 이벤트를 발생시킬 때마다 메서드가 호출됩니다.
이벤트를 발생시키고 처리하는 샘플을 보려면 방법: 이벤트 발생 및 사용을 참조하십시오.
이벤트에 대한 이벤트 처리기 메서드를 추가하려면
- 이벤트 대리자와 시그니처가 같은 이벤트 처리기 메서드를 정의합니다.
Public Class WakeMeUp
' AlarmRang has the same signature as AlarmEventHandler.
Public Sub AlarmRang(sender As Object, e As AlarmEventArgs)
'...
End Sub
'...
End Class
public class WakeMeUp
{
// AlarmRang has the same signature as AlarmEventHandler.
public void AlarmRang(object sender, AlarmEventArgs e)
{
//...
}
//...
}
public ref class WakeMeUp
{
public:
// AlarmRang has the same signature as AlarmEventHandler.
void AlarmRang(Object^ sender, AlarmEventArgs^ e)
{
//...
}
//...
};
- 이 이벤트 처리기 메서드에 대한 참조를 사용하여 대리자 인스턴스를 만듭니다. 대리자 인스턴스가 호출되면 이 인스턴스에서 이벤트 처리기 메서드를 호출합니다.
' Create an instance of WakeMeUp.
Dim w As New WakeMeUp()
' Instantiate the event delegate.
Dim alhandler As AlarmEventHandler = AddressOf w.AlarmRang
// Create an instance of WakeMeUp.
WakeMeUp w = new WakeMeUp();
// Instantiate the event delegate.
AlarmEventHandler alhandler = new AlarmEventHandler(w.AlarmRang);
// Create an instance of WakeMeUp.
WakeMeUp^ w = gcnew WakeMeUp();
// Instantiate the event delegate.
AlarmEventHandler^ alhandler = gcnew AlarmEventHandler(w, &WakeMeUp::AlarmRang);
- 이벤트에 대리자 인스턴스를 추가합니다. 이벤트가 발생하면 대리자 인스턴스 및 연결된 이벤트 처리기 메서드가 호출됩니다.
' Instantiate the event source.
Dim clock As New AlarmClock()
' Add the delegate instance to the event.
AddHandler clock.Alarm, alhandler
// Instantiate the event source.
AlarmClock clock = new AlarmClock();
// Add the delegate instance to the event.
clock.Alarm += alhandler;
// Instantiate the event source.
AlarmClock^ clock = gcnew AlarmClock();
// Add the delegate instance to the event.
clock->Alarm += alhandler;