다음을 통해 공유


방법: 이벤트 속성을 사용하여 여러 이벤트 처리

업데이트: 2007년 11월

이벤트 속성(Visual Basic 2005에서는 사용자 지정 이벤트)을 사용하려면 이벤트를 발생시키는 클래스에서 이벤트 속성을 정의한 다음 이벤트를 처리하는 클래스에서 이벤트 속성의 대리자를 설정합니다. 클래스에서 여러 이벤트 속성을 구현하려면 클래스에서는 각 이벤트에 대해 정의된 대리자를 내부적으로 저장하고 유지해야 합니다. 일반적인 방법은 이벤트 키에 의해 인덱싱된 대리자 컬렉션을 구현하는 것입니다.

각 이벤트의 대리자를 저장하려면 EventHandlerList 클래스를 사용하거나 고유의 컬렉션을 구현할 수 있습니다. 컬렉션 클래스에서는 이벤트 키를 기준으로 이벤트 처리기 대리자를 설정, 액세스 및 검색할 수 있는 메서드를 제공해야 합니다. 예를 들어 Hashtable 클래스를 사용하거나 DictionaryBase 클래스에서 사용자 지정 클래스를 파생시킬 수 있습니다. 대리자 컬렉션 구현에 대한 자세한 정보는 클래스 외부에 노출할 필요가 없습니다.

클래스 내의 각 이벤트 속성은 add 접근자 메서드와 remove 접근자 메서드를 정의합니다. 이벤트 속성의 add 접근자는 대리자 컬렉션에 입력 대리자 인스턴스를 추가합니다. 이벤트 속성의 remove 접근자는 대리자 컬렉션에서 입력 대리자 인스턴스를 제거합니다. 이벤트 속성 접근자는 이벤트 속성의 미리 정의된 키를 사용하여 대리자 컬렉션에서 인스턴스를 추가하거나 제거합니다.

이벤트 속성을 사용하여 여러 이벤트를 처리하려면

  1. 이벤트를 발생시키는 클래스 내에서 대리자 컬렉션을 정의합니다.

  2. 각 이벤트의 키를 정의합니다.

  3. 이벤트를 발생시키는 클래스에서 이벤트 속성을 정의합니다.

  4. 대리자 컬렉션을 사용하여 이벤트 속성의 add 및 remove 접근자 메서드를 구현합니다.

  5. 공용 이벤트 속성을 사용하여 이벤트를 처리하는 클래스에서 이벤트 처리기 대리자를 추가하거나 제거합니다.

예제

다음 C# 예제에서는 MouseDown 및 MouseUp 이벤트 속성을 구현하며 EventHandlerList를 사용하여 각 이벤트의 대리자를 저장합니다. 코드에서 이벤트 속성 키워드는 굵게 표시되어 있습니다.

참고:

Visual Basic 2005에서는 이벤트 속성이 지원되지 않습니다.

// The class SampleControl defines two event properties, MouseUp and MouseDown.
class SampleControl: Component {
   // :
   // Define other control methods and properties.
   // :
   
   // Define the delegate collection.
   protected EventHandlerList listEventDelegates = new EventHandlerList();
   
   // Define a unique key for each event.
   static readonly object mouseDownEventKey = new object();
   static readonly object mouseUpEventKey = new object();
   
   // Define the MouseDown event property.
   public event MouseEventHandler MouseDown {  
      // Add the input delegate to the collection.
      add { listEventDelegates.AddHandler(mouseDownEventKey, value); }
      // Remove the input delegate from the collection.
      remove { listEventDelegates.RemoveHandler(mouseDownEventKey, value); }
   }

   // Define the MouseUp event property.
   public event MouseEventHandler MouseUp {
      // Add the input delegate to the collection.
      add { listEventDelegates.AddHandler(mouseUpEventKey, value); }
      // Remove the input delegate from the collection.
      remove { listEventDelegates.RemoveHandler(mouseUpEventKey, value); }
   }
}

참고 항목

작업

방법: 메모리 사용을 줄이는 이벤트 선언

개념

여러 이벤트 발생시키기

참조

System.ComponentModel.EventHandlerList

System.Web.UI.Control.Events

기타 리소스

이벤트 처리 및 발생