Delegate : 메서드를 참조할 수 있는 타입
쉽게 말해 "메서드를 담는 변수의 타입"
메서드 시그니처(매개변수, 반환값)가 일치해야 연결 가능
특징
반환값과 매개변수 타입 지정 가능
이벤트(Event) 구현 시 자주 사용
Action/Func/Predicate = 델리게이트 일반화 버전
Delegate 예시
// 델리게이트 선언 delegate int MathOperation(int a, int b); // 메서드 int Add(int x, int y) => x + y; // 델리게이트에 메서드 연결 MathOperation op = Add; Console.WriteLine(op(3, 5)); // 8
Action : 반환값 없는 델리게이트
void만 가능
0 ~ 16개의 매개변수 가능
이벤트나 콜백에 자주 사용
Action greet = () => Console.WriteLine("Hello!"); greet(); Action<string> printName = name => Console.WriteLine(name); printName("Alice");
Action 예시
public class MyClass { public static void PrintHello() { Console.WriteLine("Hello!"); } public static void PrintSum(float a, float b) { Console.WriteLine("Sum: " + (a + b)); } } public class MainClass { public static void Main() { Action helloAction = MyClass.PrintHello; helloAction(); Action<float, float> sumAction = MyClass.PrintSum; sumAction(3.5f, 5.5f); } } // Hello! // Sum: 9
Func : 반환값 있는 델리게이트
마지막 타입 매개변수가 반환값
앞의 타입은 매개변수
Func<int, int, int> add = (a, b) => a + b; Console.WriteLine(add(3, 4)); // 7 Func<string> getGreeting = () => "Hi!"; Console.WriteLine(getGreeting());
Func 예시
using System; public class Example { public static int Add(int x, int y) { Console.WriteLine("Add: " + (x + y)); return x + y; } public static int Multiply(int x, int y) { Console.WriteLine("Multiply: " + (x * y)); return x * y; } public static void Main() { Func<int, int, int> func = Add; func += Multiply; // Func에 두 번째 메서드 추가 int result = func(3, 4); // 두 메서드를 순차적으로 호출, 마지막 메서드의 반환 값이 최종 반환됨 Console.WriteLine("Result: " + result); } } // Add: 7 // Multiply: 12 // Result: 12
Predicate : 입력값 하나 받아서 bool 반환 델리게이트
Func<T, bool>의 특수 형태
주로 조건 검사/필터링 용도
Predicate<int> isEven = n => n % 2 == 0; Console.WriteLine(isEven(4)); // True