관리 메뉴

웹개발자의 기지개

델리게이트 Delegate 연습2 (이벤트) 본문

ASP.NET/C#

델리게이트 Delegate 연습2 (이벤트)

http://portfolio.wonpaper.net 2019. 11. 16. 17:58

델리게이트 간단한 예제를 하나더 정리해 보았다.

 

Game Develper W님의 아주 좋은 포스팅 글

https://mrw0119.tistory.com/21?category=585887

 

<c# 강의=""> 7장. 이벤트 (Event)</c#>

1. 이벤트 델리게이트 타입을 선언하면 델리게이트 변수도 생성할 수 있지만, 이벤트 변수도 생성할 수 있다. 이벤트 변수는 간단히 event 한정자만 붙여주면 된다. 이벤트변수는 델리게이트 변수와 마찬가지로..

mrw0119.tistory.com

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
36
37
namespace DeleLecture
{
    // 델리게이트 타입선언
    delegate void MyDelegate(int a);
 
    class EventManager
    {
        // 이벤트 변수 선언
        public event MyDelegate eventCall;
        public void NumberCheck(int num)
        {
            if (num % 2 == 0)
                eventCall(num); // 짝수마다 이벤트 호출
        }
 
    }
 
    class Program
    {
        // 결과화면 출력메소드
        static void EvenNumber(int num)
        {
            Console.WriteLine("{0}는 짝수", num);
        }
 
        static void Main(string[] args)
        {
            EventManager em = new EventManager();
 
            // 이벤트 추가시키고 이벤트 메소드등록
            em.eventCall += new MyDelegate(EvenNumber);
 
            for (int i = 1; i <= 10; i++)                
                    em.NumberCheck(i);
        }
    }
}
cs

33번 라인상의 i값을 10번 돌리면서, NumberCheck()함수를 이벤트 동작시킨다. 

이때 짝수인 경우만 eventCall 이벤트를 호출시키는데, 실제 화면에 보여지는 출력내용은 EvenNumber 의 소스내용이다.

 

Comments