델리게이트(Delegate) 는 메서드를 참조할 수 있는 타입(포인터 역할) 이다.
즉, 메서드를 변수처럼 저장하고 전달할 수 있는 기능을 제공한다.
Invoke(), () 사용)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
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
}
}
델리게이트는 여러 개의 메서드를 등록하여 한 번에 실행할 수도 있다.
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
Func<T>, Action<T> 델리게이트C#에서는 델리게이트를 직접 정의하지 않고도 사용 가능한 표준 델리게이트(Func<>, Action<>)를 제공한다.
Func<T> (리턴값이 있는 델리게이트)Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(3, 5)); // 8 출력
Func<T1, T2, TResult>는 매개변수를 받고 값을 반환하는 델리게이트 이다.Action<T> (리턴값이 없는 델리게이트)Action<string> printMessage = message => Console.WriteLine(message);
printMessage("Hello!"); // Hello! 출력
Action<T>는 반환값 없이 실행되는 델리게이트 이다.Predicate<T> (조건을 검사하는 델리게이트)Predicate<int> isEven = x => x % 2 == 0;
Console.WriteLine(isEven(4)); // True 출력
Predicate<T>는 bool을 반환하는 델리게이트 이다.델리게이트는 이벤트 시스템을 구현할 때 필수적으로 사용된다.
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; |