[C#] 델리게이트와 이벤트 (Delegates and Events)

Yijun Jeon·2023년 9월 13일
0

C#

목록 보기
1/7
post-thumbnail

델리게이트(Delegate)

델리게이트는 한마디로 대리자라고 말할 수 있다. 즉, 메소드 참조를 포함하고 있는 영역

  • 선언 형식
delegate 반환형 델리게이트명(매개변수...);

델리게이트를 이용해서 메소드를 넘겨줄 수 있다. 델리게이트는 메소드를 참조 하는 것이고, 참조하는 메소드가 달라진다면 델리게이트 역시 달라짐

매개변수의 데이터 형식,개수와 반환형은 참조할 메소드의 매개변수의 데이터 형식과 맞추어야 함!

  • 사용 예제
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication39
{
    delegate int PDelegate(int a, int b);

    class Program
    {
        static int Plus(int a, int b)
        {
            return a + b;
        }

        static void Main(string[] args)
        {
            PDelegate pd1 = Plus;
            PDelegate pd2 = delegate(int a, int b)
            {
                return a / b;
            };

            Console.WriteLine(pd1(5, 10));
            Console.WriteLine(pd2(10, 5));
        }
    }
}

결과 :

15
2

델리게이트 체인(Delegate chain)

델리게이트 체인은 델리게이트 하나를 가지고 여러개의 메소드를 한번에 호출할 수 있게 함

  • 사용 예제
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication39
{
    delegate void PDelegate(int a, int b);

    class Program
    {
        static void Plus(int a, int b)
        {
            Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
        }

        static void Minus(int a, int b)
        {
            Console.WriteLine("{0} - {1} = {2}", a, b, a - b);
        }

        static void Division(int a, int b)
        {
            Console.WriteLine("{0} / {1} = {2}", a, b, a / b);
        }

        static void Multiplication(int a, int b)
        {
            Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
        }

        static void Main(string[] args)
        {
            PDelegate pd = (PDelegate)Delegate.Combine(new PDelegate(Plus),
                new PDelegate(Minus), new PDelegate(Division), new PDelegate(Multiplication));

            pd(20, 10);
        }
    }
}

결과 :

20 + 10 = 30
20 - 10 = 10
20 / 10 = 2
20 * 10 = 200

이벤트(Event)

이벤트는 '특정 사건이 벌어지면 알리는 메세지'라 할 수 있다.
ex) 버튼 클릭, 게임 시작, 창 닫거나 엶..

델리게이트를 사용하여 이벤트를 처리할 수 있음

  • 선언 형식
한정자 event 델리게이트 이름;
  • 사용 예제
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication42
{
    public delegate void MyEventHandler(string message);

    class Publisher
    {
        public event MyEventHandler Active;

        public void DoActive(int number)
        {
            if (number % 10 == 0)
                Active("Active!" + number);
            else
                Console.WriteLine(number);
        }
    }

    class Subscriber
    {
        static public void MyHandler(string message)
        {
            Console.WriteLine(message);
        }

        static void Main(string[] args)
        {
            Publisher publisher = new Publisher();
            publisher.Active += new MyEventHandler(MyHandler);

            for (int i = 1; i < 50; i++)
                publisher.DoActive(i);
        }
    }
}

결과 :

1

..

Active!10

..

Active!40

..

49

Reference

https://blog.hexabrain.net/151
https://www.youtube.com/watch?v=m9_D0DQ4SGU

0개의 댓글