1. 이벤트 핸들러란?
데이터를 생성하지 않는 이벤트에 대한 이벤트 처리기 메소드를 말한다.
.NET 프레임워크에서 이벤트는 관찰자 패턴인 Delegate 모델을 기반으로 하는데, 이는 구독자로 하여금 등록을 가능하게 하고, 공급자로부터 알림을 받게한다. 이벤트 송신자는 이벤트가 발생했음을 알리고, 이벤트 수신자는 해당 알림을 수신하고 그에 대한 응답을 정의한다.
이벤트 처리를 위해서는 다음 4가지의 항목이 필요하다.
1) 이벤트 클래스 : ThresholdReached라는 이벤트를 선언한다.
class Counter { public event EventHandler ThresholdReached; protected virtual void OnThresholdReached(EventArgs e) { EventHandler handler = ThresholdReached; if (handler != null) { handler(this, e); } } // provide remaining implementation for the class }
일반적으로 이벤트를 발생시키려면 protected와 virtual 또는 protected와 overridable 메소드를 추가해야 한다. 이 메소드는 이벤트 데이터 개체를 지정하는 하나의 매개변수를 취해야 한다.
파생된 클래스는 등록된 Delegate가 이벤트를 수신할 수 있도록 해주는 기본 클래스의 OnEventName 메소드를 항상 호출해야 한다.
2) Delegate(메소드에 대한 참조)
public delegate void ThresholdReachedEventHandler(object sender, ThresholdReachedEventArgs e);
3) 이벤트 데이터
public class ThresholdReachedEventArgs : EventArgs { public int Threshold { get; set; } public DateTime TimeReached { get; set; } }
이벤트와 관련된 데이터는 이벤트 데이터 클래스를 통해 제공할 수 있다. EventArgs 클래스는 모든 이벤트 데이터 클래스의 기본 형식이다. 다른 클래스에게 어떤 일이 발생했으며 어떤 데이터도 전달할 필요가 없다는 것을 알리기만 하는 이벤트를 만들려면 Delegate에서 두 번째 매개변수로 EventArgs클래스를 포함하면 된다. EventHandler Delegate는 매개변수로 EventArgs클래스를 포함한다.
4) 이벤트 처리기
class Program { static void Main(string[] args) { Counter c = new Counter(); c.ThresholdReached += c_ThresholdReached; // provide remaining implementation for the class } static void c_ThresholdReached(object sender, EventArgs e) { Console.WriteLine("The threshold was reached."); } }
이벤트가 발생할 때 알림을 받기 위해서는 이벤트 처리기 메소드에서 이벤트를 구독(+=)해야 한다.
미리 정의된 형식 'System.ValueTuple`2'을(를) 정의하지 않았거나 가져오지 않았습니다. (0) | 2019.02.13 |
---|---|
LINQ (0) | 2019.02.13 |
Lambda Expression (0) | 2019.02.12 |
Delegate (0) | 2019.01.29 |
Visual Studio 2017 자주 쓰는 단축키 목록 (0) | 2019.01.20 |