C#

[C#] - 이벤트(event), 이벤트 핸들러(EventHandler)

Riucc 2019. 4. 8. 23:30

○ 이벤트(event), 이벤트 핸들러(EventHandler)

 

- event(이벤트)

     특정 상황이 발생했을 때, 알리고자 하는 용도(호출 + 데이터)

     델리게이트를 기반으로 한다(메소드 호출, 메소드에 집중)

     이벤트는 메소드 안에서만 사용가능(밖에서는 사용불가)


     이벤트 핸들러에 객체의 메소드를 연결

     이벤트 핸들러는 객체 메소드에서 호출

     이벤트 핸들러를 메소드를 통해 다른 객체 또는 객체의 매소드를 호출하기 위한 방법


     이벤트에 메소드 추가 및 삭제 : +=, -=

        객체.이벤트 핸들러 += new 델리게이트형(객체.메소드1);   // 1.0 버전

        객체.이벤트 핸들러 += 객체.메소드1   // 2.0 버전

        객체.이벤트 핸들러 -= 객체.메소드2    // += 추가, -= 삭제


1
2
3
4
5
6
7
8
9
10
11
12
13
// 이벤트 기본 형식
 
[접근 한정자] event 델리게이트형 이벤트명
delegate void DelegateType(string message);
 
class A
{
     public event DelegateType EventHandler;
     public void Func(string Message)
     {
          EventHandler(Message);
     }
}
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
delegate void DelegateType(string message);
 
class A
{
    public event DelegateType EventHandler;
    public void Func(string Message)
    {
        EventHandler(Message);
    }
}
 
class B
{
    public void PrintA(string Message)
    {
        Console.WriteLine(Message);
    }
    public void PrintB(string Message)
    {
        Console.WriteLine(Message);
    }
}
 
A Test1 = new A();
B Test2 = new B();
 
Test1.EventHandler += new DelegateType(Test2.PrintA); // 1.0 버전
Test1.EventHandler += new DelegateType(Test2.PrintB);
Test1.Func("Goooood");
Test1.EventHandler -= Test2.PrintB; // 2.0 버전
Test1.Func("HDDDDDD");
Test1.EventHandler -= Test2.PrintA;
Test1.EventHandler += Test2.PrintA;
Test1.Func("1111111");
// Goooood Goooood HDDDDDD 111111 출력
cs