C#에서는 메서드를 변수에 담아서 전달하거나 나중에 호출할 수 있다.
이때 사용하는 것이 델리게이트(delegate) 인데, Action과 Func는 그 중 가장 자주 쓰이는 내장 델리게이트 타입이다.
Action은 반환값이 없는(void) 메서드를 담는 델리게이트다.
Action greet = () => Console.WriteLine("ㅇㅇ");
greet(); // 축약형 호출
greet.Invoke(); // 명시적 호출 (둘 다 동일)
매개변수가 있으면 제네릭으로 타입을 명시한다.
Action<string> printName = (name) => Console.WriteLine($"이름: {name}");
printName("재구"); // 이름: 재구
매개변수가 여러 개면 순서대로 타입을 나열한다.
Action<string, int> printInfo = (name, age) => Console.WriteLine($"이름: {name}, 나이: {age}");
printInfo("재구", 28); // 이름: 재구, 나이: 28
| 타입 | 설명 |
|---|---|
| Action | 매개변수 없음 |
| Action<T> | 매개변수 1개 |
| Action<T1, T2, T3> | 개변수 3개 (최대 16개까지 지원) |
Func는 반환값이 있는 메서드를 담는 델리게이트다.
핵심 규칙 : 마지막 타입이 항상 반환 타입이다.
Func<int, int, int> add = (a, b) => a + b;
int result = add(3, 5);
Console.WriteLine(result); // 8
Func<int, int, int> — int 두 개를 받아서 int를 반환한다는 의미.
// string을 받아서 string을 반환
Func<string, string> getGreeting = (name) => $"안녕, {name}";
Console.WriteLine(getGreeting("재구")); // 안녕, 재구
// int 두 개를 받아서 int를 반환
Func<int, int, int> multiply = (a, b) => a * b;
Console.WriteLine(multiply(4, 6)); // 24
| 타입 | 설명 |
|---|---|
| Func | 매개변수 없음 |
| Func<T, TResult> | 매개변수 1개, TResult 반환 |
| Func<T1, T2, TResult> | 매개변수 2개, TResult 반환 |
| - | Action | Func |
|---|---|---|
| 반환값 | 없음 (void) | 있음 |
| 선언 예시 | Action<string> | Func<string, int> |
| 마지막 타입 | 매개변수 | 반환 타입 |
| 사용 예 | 출력, 이벤트 처리 | 계산, 값 변환 |
Action은 Unity에서 이벤트 시스템에 자주 쓰인다.
public class GameManager : MonoBehaviour
{
public static Action OnGameOver; // 게임 오버 이벤트
void Update()
{
if (playerHP <= 0)
OnGameOver?.Invoke(); // 구독한 메서드 전부 호출
}
}
Func는 조건 판별이나 값 계산을 외부에서 주입할 때 유용하다.
// 점수 계산 방식을 외부에서 주입
void ApplyScore(int baseScore, Func<int, int> scoreCalculator)
{
int final = scoreCalculator(baseScore);
Debug.Log($"최종 점수: {final}");
}
ApplyScore(100, score => score * 2); // 최종 점수: 200