Delegate (델리게이트)

최장범·2023년 11월 3일

공부

목록 보기
10/24

델리게이트

델리게이트 (Delegate)

  • 델리게이트란?
    • 다른 메서드를 참조하는 개체
    • 메서드를 인수로 전달, 또는 변수에 할당하여 다른 메서드를 호출할 수 있는 방법을 제공한다.
    • 이벤트 처리, 비동기 프로그래밍, 콜백 함수 드을 구현하는데 유용하다.

특징

  • 메서드를 참조한다.

    • 특정 매개변수 및 반환 유형의 메서드를 가리킨다.
  • 다중 메서드 호출이 가능하다.

    • 여러 메서드를 한번에 호출할 수 있도록 델리게이트 인스턴스에 추가할 수 있다.
  • 콜백 함수를 지정하는데 사용된다.

  • 델리게이트는 C#의 이벤트, LINQ(언어 통합 쿼리), 콜백 메커니즘 등에서 널리 사용.

  • 또한 델리게이트는 코드의 유연성과 재사용성을 높이며, 프로그램의 확장성을 향상시키는 데 도움이 된다.


using System;

public delegate void MyDelegate(string message); // 델리게이트 정의

public class DelegateExample {
    public void Method1(string message) {
        Console.WriteLine("Method 1: " + message);
    }

    public void Method2(string message) {
        Console.WriteLine("Method 2: " + message);
    }
}

public class Program {
    public static void Main() {
        DelegateExample example = new DelegateExample();

        MyDelegate del = example.Method1; // 델리게이트에 Method1 추가
        del += example.Method2; // 델리게이트에 Method2 추가

        // 델리게이트를 호출하여 메서드 실행
        del("Hello, delegates!");

        // 비동기적 프로그래밍에서 콜백 함수로 사용하는 예시
        Action<string> callback = new Action<string>(example.Method1);
        SomeAsyncMethod("Hello, async delegates!", callback);
    }

    public static void SomeAsyncMethod(string message, Action<string> callback) {
        // 비동기적 작업 수행
        Console.WriteLine("Doing some async work...");
        // 작업이 완료된 후 콜백 함수 호출
        callback(message);
    }
}

0개의 댓글