본문 바로가기
코딩연습/C#

[C#]대리자의 이벤트

by 호아니 2020. 6. 12.

<구현>

1.대리자선언(클래스 안 또는 밖)

2.클래스 내에 선언한 대리자의 인스턴스를 event한정자로 수식해서 선언함

3.이벤트 핸들러 작성

4.클래스의 인스턴스 생성하고 이벤트 핸들러를 등록

5. 이벤트가 발생하면 이벤트 헨들러가 호출됨

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp12
{
    class Program
    {
        delegate void EventHandler(string message);//대리자선언

        class MyNotifier
        {
            public event EventHandler SomethingHappend;//클래스 내에 선언한 대리자의 인스턴스를 event한정자로 수식해서 선언함
            public void DoSomething(int number)
            {
                int temp = number % 10;
                if ((temp != 0 && temp % 3 == 0))
                    SomethingHappend(String.Format("{0}:짝", number));
            }
        }
        static public void Myhandler(string message)//이벤트 핸들러 작성
        {
            Console.WriteLine(message);
        }
        static public void Myhandler2(string message)
        {
            Console.WriteLine("MyHandler2");
        }
        static void Main(string[] args)
        {   
          

            MyNotifier notifier = new MyNotifier();클래스의 인스턴스 생성
            notifier.SomethingHappend += new EventHandler(Myhandler);//이벤트 핸들러를 등록
            notifier.SomethingHappend += new EventHandler(Myhandler2);//이벤트 핸들러를 등록

            for (int i = 1; i < 30; i++)
            {
                notifier.DoSomething(i); //이벤트 발생시 이벤트 핸들러 호출
            }
        }
    }
}

'코딩연습 > C#' 카테고리의 다른 글

[C#]LINQ연습문제(레코드조회)  (0) 2020.06.12
[C#]LINQ  (0) 2020.06.12
[C#]대리자 체인  (0) 2020.06.12
[C#]대리자(delegate)  (0) 2020.06.12
[C#]강제로 예외던지기(throw)  (0) 2020.06.12