델리게이트(Delegate)

Shy·2025년 3월 17일

C#

목록 보기
23/27

델리게이트(Delegate)

델리게이트(Delegate) 는 메서드를 참조할 수 있는 타입(포인터 역할) 이다.

즉, 메서드를 변수처럼 저장하고 전달할 수 있는 기능을 제공한다.

  • 메서드를 변수처럼 다룰 수 있음 (메서드의 "주소"를 저장)
  • 다른 메서드를 실행할 수 있음 (Invoke(), () 사용)
  • 다중 메서드 연결(Multicast) 가능 (여러 개의 메서드를 한 번에 실행)
  • 이벤트(Event)에서 많이 사용됨

1. 기본 델리게이트 예제

using System;

class Program
{
    // 1. 델리게이트 정의 (int를 받아 int를 반환하는 함수 저장 가능)
    delegate int MathOperation(int x, int y);

    // 2. 델리게이트가 참조할 메서드들
    static int Add(int a, int b) => a + b;
    static int Multiply(int a, int b) => a * b;

    static void Main()
    {
        // 3. 델리게이트 인스턴스 생성
        MathOperation operation;

        // 4. Add 메서드를 참조하도록 설정
        operation = Add;
        Console.WriteLine(operation(3, 4)); // 7 출력

        // 5. Multiply 메서드를 참조하도록 변경
        operation = Multiply;
        Console.WriteLine(operation(3, 4)); // 12 출력
    }
}

출력

7
12
  • 델리게이트를 사용하면 특정 메서드를 참조하고 실행할 수 있다.

2. 델리게이트의 다양한 사용법

(1) 델리게이트를 사용한 메서드 전달

using System;

class Program
{
    delegate void PrintMessage(string message);

    static void PrintHello(string message) => Console.WriteLine($"Hello, {message}");
    static void PrintGoodbye(string message) => Console.WriteLine($"Goodbye, {message}");

    static void Execute(PrintMessage printer, string text)
    {
        printer(text); // 전달된 델리게이트 실행
    }

    static void Main()
    {
        Execute(PrintHello, "Alice"); // Hello, Alice
        Execute(PrintGoodbye, "Bob"); // Goodbye, Bob
    }
}
  • 델리게이트를 사용하면 특정 메서드를 매개변수로 전달할 수 있다.

(2) 다중 델리게이트 (Multicast Delegate)

델리게이트는 여러 개의 메서드를 등록하여 한 번에 실행할 수도 있다.

using System;

class Program
{
    delegate void Notify(); // 반환값이 없는 델리게이트

    static void ShowMessage1() => Console.WriteLine("Message 1");
    static void ShowMessage2() => Console.WriteLine("Message 2");

    static void Main()
    {
        Notify notify = ShowMessage1;
        notify += ShowMessage2; // 다중 메서드 등록

        notify(); // Message 1, Message 2 출력
    }
}

출력

Message 1
Message 2
  • 여러 개의 메서드를 등록하여 한 번에 실행할 수 있다.

3. Func<T>, Action<T> 델리게이트

C#에서는 델리게이트를 직접 정의하지 않고도 사용 가능한 표준 델리게이트(Func<>, Action<>)를 제공한다.

(1) Func<T> (리턴값이 있는 델리게이트)

Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(3, 5)); // 8 출력
  • Func<T1, T2, TResult>는 매개변수를 받고 값을 반환하는 델리게이트 이다.

(2) Action<T> (리턴값이 없는 델리게이트)

Action<string> printMessage = message => Console.WriteLine(message);
printMessage("Hello!"); // Hello! 출력
  • Action<T>는 반환값 없이 실행되는 델리게이트 이다.

(3) Predicate<T> (조건을 검사하는 델리게이트)

Predicate<int> isEven = x => x % 2 == 0;
Console.WriteLine(isEven(4)); // True 출력
  • Predicate<T>bool을 반환하는 델리게이트 이다.

4. 델리게이트와 이벤트(Event)

델리게이트는 이벤트 시스템을 구현할 때 필수적으로 사용된다.

using System;

class Button
{
    public delegate void ClickHandler();
    public event ClickHandler OnClick;

    public void Click()
    {
        OnClick?.Invoke(); // 등록된 메서드 실행
    }
}

class Program
{
    static void Main()
    {
        Button button = new Button();

        button.OnClick += () => Console.WriteLine("Button Clicked!");
        button.Click(); // Button Clicked! 출력
    }
}
  • 델리게이트를 사용하면 이벤트를 쉽게 구현할 수 있다.

정리

개념설명
델리게이트(Delegate)메서드를 참조하고 실행할 수 있는 타입
델리게이트 선언delegate int MathOperation(int x, int y);
델리게이트 사용MathOperation op = Add;
다중 델리게이트notify += ShowMessage2;
Func<T>Func<int, int, int> add = (x, y) => x + y;
Action<T>Action<string> print = msg => Console.WriteLine(msg);
Predicate<T>Predicate<int> isEven = x => x % 2 == 0;
이벤트(Event)에서 사용public event ClickHandler OnClick;
  • 즉, 델리게이트는 메서드를 저장하고 실행할 수 있는 기능을 제공하는 중요한 개념이다.
profile
신입사원...

0개의 댓글