대리자 Delegate

Gogi·2023년 9월 6일

C# 언어 기초 목록

목록 보기
18/29

메소드에 대한 참조를 저장하는 타입

딜리게이트는 C#에서 메소드에 대한 참조를 저장하는 타입이다. 딜리게이트를 사용하면 메소드를 변수처럼 저장, 전달, 호출할 수 있다. C++의 함수 포인터, std::function과 유사한 역할을 한다.


개념 설명

딜리게이트는 메소드의 시그니처를 따라 선언된다. 예를 들어, 반환 타입이 int이고 정수 두 개를 파라미터로 받는 메소드에 대한 딜리게이트는 다음과 같이 선언할 수 있다.

public delegate int MyDelegate(int x, int y);

사용 예시

딜리게이트에 메소드를 할당하고,
해당 딜리게이트를 통해 메소드를 호출할 수 있다.

- 멀티 캐스트 (MultiCast)

여러 메소드를 하나의 딜리게이트 인스턴스에 할당하고 일괄적으로 호출할 수 있다.

using System;

namespace DelegateExample
{
    public delegate void MyDelegate(int a, int b);

    class Program
    {
        static void Add(int a, int b)
        {
            Console.WriteLine($"Addition: {a + b}");
        }

        static void Subtract(int a, int b)
        {
            Console.WriteLine($"Subtraction: {a - b}");
        }

        static void Main(string[] args)
        {
            // 딜리게이트 인스턴스
            MyDelegate addDel = Add;
            MyDelegate subDel = Subtract;

			// 딜리게이트 실행
            addDel(10, 5);  // 출력: Add 15
            subDel(10, 5);  // 출력: Subtract 5

            // 멀티캐스트
            MyDelegate multiDel = addDel + subDel;
            multiDel(20, 10);  // 출력: Add 30
                               // 출력: Subtract 10
        }
    }
}

- 이벤트와의 관계

델리게이트는 C#에서 이벤트를 구현할 때도 많이 사용된다. 이벤트는 특정 액션에 응답하여 메서드를 실행하는 매커니즘을 제공하는데, 이때 델리게이트가 이 메서드를 참조한다.

public class MyEventPublisher
{
    // 델리게이트 선언
    public delegate void MyEventHandler(string message);
    
    // 이벤트 선언
    public event MyEventHandler MyEvent;

    public void RaiseEvent(string message)
    {
        // 이벤트 발생시키기
        MyEvent?.Invoke(message);
    }
}
profile
C, C++, C#, Unity

0개의 댓글