이번 시간에는 Delegate와 Action, Func에 대해 알아보고 활용해보는 시간을 가지겠다.
1. Delegate
// 기본적으로 하나의 변수에 다른 변수를 넣을 수 있음
int value;
int a = 1;
int b = 2;
value = a;
value = b;
// 델리게이트(Delegate 또한 함수를 참조하여 그 함수를 활용할 수 있다.
public int Add(int a, int b) => a + b;
delegate int MyDelegate(int a, int b);
MyDelegate myDelegate = Add;
int sum = myDelegate(1, 2);
델리게이트(Delegate)란 메서드를 참조하는 포인터 타이다. 이를 이용하면 메서드를 매개변수로 전달하거나 변수에 할당 할 수 있다.
public int Add(int a, int b) => a + b;
public int Subtract(int a, int b) => a - b;
delegate int MyDelegate(int a, int b);
MyDelegate myDelegate;
myDelegate = Add;
myDelegate += Subtract
또한 메서드를 여러개 추가하여 한꺼번에 처리할 수 있기 때문에 델리게이트는 어떤 행위가 이뤄질때 다른 행위가 처리가 필요한 메서드들을 다 예약하는 기능으로 많이 활용한다.
2. Action
class Program
{
static void Greet(string name) => Console.WriteLine("Hello " + name);
static void Main()
{
Action<string> sayHello = Greet;
sayHello("Alice"); // 출력: Hello Alice
// 람다식도 가능
Action<int, int> add = (a, b) => Console.WriteLine(a + b);
add(3, 5); // 출력: 8
}
}
Action은 .NET에서 미리 정의한 제너럴 델리게이트 타입이다. 반환값이 없는 메서드를 참조할 때 사용한다.
따라서 주로 반환이 필요없는 이벤트 처리나 콜벡 처리를 할 때 많이 사용한다.
3. Func
class Program
{
static void Greet(string name) => Console.WriteLine("Hello " + name);
static void Main()
{
Action<string> sayHello = Greet;
sayHello("Alice"); // 출력: Hello Alice
// 람다식도 가능
Action<int, int> add = (a, b) => Console.WriteLine(a + b);
add(3, 5); // 출력: 8
}
}
Func 또한 .NET에서 미리 정의한 제너럴 델리게이트 타입으로 Action과 다르게 반환값이 있는 메서드를 참조할 때 사용한다.
4. 델리게이트 활용
private Action currentView; // 현재 창 (시작창, 스탯창 등)
public override void Start()
{
// 처음 View 설정: StarView
currentView = StartView;
}
public override void Update()
{
// View 변할 때 마다 실행
currentView?.Invoke();
}
// 메뉴 열기
private void StartView()
{
Console.Clear();
uiManager.OpenMenu();
var choice = GetUserChoice(["1", "2"]);
currentView = choice == "1" ? StateView : InventoryView;
}
// 상태 보기
private void StateView()
{
Console.Clear();
uiManager.ShowState(character);
var choice = GetUserChoice(["0"]);
currentView =StartView;
}
// 인벤토리 보기
private void InventoryView()
{
Console.Clear();
uiManager.ShowInventory(character.Inventroy);
var choice = GetUserChoice(["0", "1"]);
currentView = choice == "0" ? StartView : InventoryEquippedView;
}
한 Scene에서 조건에 따라 여러 UI를 보여주는 함수들을 호출한다면, 델리게이트 타입을 활용하여 이를 활용할 수 있다.
위 코드에서는 사용자에 입력에 따라 Action 참조 함수를 다를게 하여 참조 객체가 바뀔 때 그 함수를 호출하는 형식으로 여러가지 View를 표현하였다.
이 외에도 개인적으로 상태 머신(State Machine)에도 활용할 수 있을 것 같다.
'프로그래밍 > CS + 문법' 카테고리의 다른 글
C# 콘솔 문자열 덮어쓰기 (0) | 2025.10.03 |
---|---|
Unity 자료구조 (1) | 2025.09.19 |
Unity get / set (0) | 2025.09.17 |
Unity 스크립트 기본 클래스 정리 (0) | 2025.09.12 |