[C#] delegate(델리게이트)

동키·2024년 12월 26일

C#

목록 보기
10/12

delegate(델리게이트)는 C#에서 메서드 참조를 저장하고 호출할 수 있는 형식입니다. 델리게이트는 메서드를 변수처럼 취급할 수 있게 해주며, 특히 동적 메서드 호출이나 이벤트 처리에 유용하게 사용됩니다.

델리게이트란?

  • 델리게이트는 메서드에 대한 참조(주소)를 저장하는 객체입니다.
  • 특정 메서드를 실행하거나, 동적으로 메서드를 교체하거나, 여러 메서드를 한 번에 실행할 수 있습니다.

델리게이트의 특징

  1. 형식 안전(Type-Safe): 델리게이트는 지정된 메서드 시그니처(리턴 타입과 매개변수)를 반드시 따릅니다.
  2. 동적으로 메서드 참조: 프로그램 실행 중에 호출할 메서드를 변경할 수 있습니다.
  3. 이벤트 처리의 기반: 델리게이트는 C#의 이벤트 처리를 구현하는 기본 구성 요소입니다.

delegate 선언 및 사용

  1. delegate 선언
  delegate int MyDelegate(int x, int y); // 반환 타입: int, 매개변수: (int x, int y)
  1. 사용 예제
  using System;

  class Program
{
    // 델리게이트 선언
    delegate int MyDelegate(int x, int y);

    static void Main()
    {
        // 델리게이트 인스턴스 생성 (Add 메서드 참조)
        MyDelegate del = Add;

        // 델리게이트 호출
        int result = del(3, 5);
        Console.WriteLine($"Result: {result}"); // 출력: Result: 8
    }

    static int Add(int a, int b)
    {
        return a + b;
    }
}
  1. 델리게이트와 메서드 교체
using System;

class Program
{
    delegate int MyDelegate(int x, int y);

    static void Main()
    {
        MyDelegate del = Add; // Add 메서드 참조
        Console.WriteLine(del(3, 5)); // 출력: 8

        del = Multiply; // Multiply 메서드 참조
        Console.WriteLine(del(3, 5)); // 출력: 15
    }

    static int Add(int a, int b)
    {
        return a + b;
    }

    static int Multiply(int a, int b)
    {
        return a * b;
    }
}

  
  • 델리게이트의 메서드를 동적으로 변경할 수 있습니다.

멀티캐스트 델리게이트

  • 델리게이트는 여러 메서드를 참조할 수 있습니다.
  • += 연산자를 사용하여 여러 메서드를 추가할 수 있습니다.
  • 반환값이 있는 델리게이트의 경우, 마지막 메서드의 반환값만 사용됩니다.
using System;

class Program
{
    delegate void MyDelegate(string message);

    static void Main()
    {
        MyDelegate del = PrintMessage1;
        del += PrintMessage2; // 두 번째 메서드 추가

        // 두 메서드 실행
        del("Hello, Delegate!");
    }

    static void PrintMessage1(string message)
    {
        Console.WriteLine($"Message1: {message}");
    }

    static void PrintMessage2(string message)
    {
        Console.WriteLine($"Message2: {message}");
    }
}
출력
Message1: Hello, Delegate!
Message2: Hello, Delegate!

Func와 Action으로 델리게이트 간소화

Func

  • 반환값이 있는 델리게이트를 정의합니다.
  • 마지막 제네릭 매개변수가 반환 타입을 나타냅니다.
Func<int, int, int> add = (a, b) => a + b; // 두 정수를 더하는 람다 식
Console.WriteLine(add(3, 5)); // 출력: 8

Action

  • 반환값이 없는 델리게이트를 정의합니다.
Action<string> printMessage = message => Console.WriteLine(message);
printMessage("Hello, Action!"); // 출력: Hello, Action!

델리게이트의 장점

동적 메서드 호출:

  • 실행 중에 호출할 메서드를 변경하거나, 여러 메서드를 순차적으로 호출 가능.

유연성:

  • 메서드 호출 방식과 순서를 유연하게 관리.

이벤트 처리:

  • 이벤트 기반 프로그래밍의 핵심 도구.

코드 재사용성:

  • 다양한 메서드 호출 시나리오에 재사용 가능.
profile
오키동키

0개의 댓글