Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# 델리게이트(Delegate) 선언 방법과 활용 예제 총정리

C#에서 델리게이트(Delegate)는 메서드에 대한 참조를 저장하는 특수한 형식입니다. 델리게이트는 하나 이상의 메서드에 대한 참조를 보유할 수 있는 참조 형식(reference type) 변수로, 런타임에 참조하는 메서드를 자유롭게 변경할 수 있다는 것이 큰 특징입니다.

델리게이트란 무엇인가?

델리게이트는 C++의 함수 포인터와 유사하지만, 타입 안전성(type-safe)을 보장한다는 점에서 차이가 있습니다. 주로 다음과 같은 용도로 활용됩니다.

  • 이벤트(Event) 구현
  • 콜백(Callback) 메서드 처리
  • 메서드를 매개변수로 전달하는 고차 함수 패턴

C#의 모든 델리게이트는 암묵적으로 System.Delegate 클래스로부터 파생됩니다.

델리게이트 선언 문법

델리게이트는 아래와 같은 형식으로 선언합니다.

delegate <반환 타입> <델리게이트 이름> <매개변수 목록>

예를 들어 문자열을 받고 반환값이 없는 델리게이트는 다음과 같이 선언할 수 있습니다.

public delegate void printString(string s);

델리게이트 사용 예제

다음 예제는 하나의 델리게이트를 사용해 화면 출력과 파일 출력이라는 서로 다른 두 메서드를 호출하는 방법을 보여줍니다.

using System;
using System.IO;

namespace DelegateAppl {

    class PrintString {
        static FileStream fs;
        static StreamWriter sw;

        // 델리게이트 선언
        public delegate void printString(string s);

        // 콘솔에 출력하는 메서드
        public static void WriteToScreen(string str) {
            Console.WriteLine("The String is: {0}", str);
        }

        // 파일에 출력하는 메서드
        public static void WriteToFile(string s) {
            fs = new FileStream("c:\\message.txt",
            FileMode.Append, FileAccess.Write);
            sw = new StreamWriter(fs);
            sw.WriteLine(s);
            sw.Flush();
            sw.Close();
            fs.Close();
        }

        // 델리게이트를 매개변수로 받아 필요한 메서드를 호출
        public static void sendString(printString ps) {
            ps("Hello World");
        }

        static void Main(string[] args) {
            printString ps1 = new printString(WriteToScreen);
            printString ps2 = new printString(WriteToFile);
            sendString(ps1);
            sendString(ps2);
            Console.ReadKey();
        }
    }
}

실행 결과

The String is: Hello World

예제 코드 해설

위 코드의 핵심 흐름은 다음과 같습니다.

  1. printString 델리게이트를 선언하여 문자열 매개변수를 받는 메서드 시그니처를 정의합니다.
  2. Main 메서드에서 WriteToScreenWriteToFile 메서드를 각각 델리게이트 인스턴스(ps1, ps2)에 연결합니다.
  3. sendString 메서드는 델리게이트를 매개변수로 전달받아, 연결된 실제 메서드를 실행합니다.

이처럼 델리게이트를 활용하면 메서드 자체를 데이터처럼 전달할 수 있어, 상황에 따라 다른 동작을 유연하게 수행하는 코드를 작성할 수 있습니다. 이는 이벤트 처리나 비동기 프로그래밍에서 매우 중요한 기반 개념이 됩니다.