[C#] 델리게이트
[C#] 델리게이트
델리게이트
- 델리게이트(delegate)는 메서드를 참조하는 타입입니다. (다른 프로그래밍 언어에서는 함수 포인터라고도 한다)
- 델리게이트를 이용하면 메서드를 매개변수로 전달하거나 변수에 할당할 수 있다.
기본 코드
- 메서드 등록 및 사용
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
delegate int Calculate(int x, int y); static int Add(int x, int y) { return x + y; } class Program { static void Main() { // 메서드 등록 Calculate calc = Add; // 델리게이트 사용 int result = calc(3, 5); Console.WriteLine("결과: " + result); } }
- 하나 이상의 메서드 등록
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
delegate void MyDelegate(string message); static void Method1(string message) { Console.WriteLine("Method1: " + message); } static void Method2(string message) { Console.WriteLine("Method2: " + message); } class Program { static void Main() { // 델리게이트 인스턴스 생성 및 메서드 등록 MyDelegate myDelegate = Method1; myDelegate += Method2; // 델리게이트 호출 myDelegate("Hello!"); Console.ReadKey(); } }
멀티캐스트 델리게이트
한 번에 여러 메서드를 실행할 수 있다. 연속적으로 실행해야 할 때, 여러 개의 메서드를 덧셈(+=)으로 연결해서 한 번에 실행할 수 있다. 여러 메서드를 한 번에 다룰 수 있기 때문에, 게임처럼 여러 가지 동작을 동시에 처리할 때 유용합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;
class Game
{
delegate void CharacterAction(); // 행동을 나타내는 델리게이트
static void Jump()
{
Console.WriteLine("점프!");
}
static void Run()
{
Console.WriteLine("달리기!");
}
static void Attack()
{
Console.WriteLine("공격!");
}
static void Main()
{
// 여러 메서드를 하나의 델리게이트에 묶기
CharacterAction actions = Jump;
actions += Run; // 덧셈으로 메서드를 추가
actions += Attack; // 덧셈으로 메서드를 추가
// 모든 행동을 순차적으로 실행
actions(); // 점프, 달리기, 공격 순으로 실행됨
}
}
This post is licensed under CC BY 4.0 by the author.
