728x90
반응형
Delegate
C#에서 Delegate는 C++의 함수 포인터와 비슷한 개념으로 메서드를 참조하는데 사용됩니다.
delegate는 메서드의 형식을 정의하며, 특정 형식의 메서드에 대한 참조를 담을 수 있으며,
이를 통해 메서드를 인자로 전달하거나, 이벤트 처리를 할 수 있는 기능을 제공합니다.
Delegate의 특징
- 메서드 참조 : delegate는 메서드를 가리킬 수 있으며, 메서드를 변수처럼 다룰 수 있습니다.
- 멀티캐스트 : 하나의 delegate 인스턴스에 여러 메서드 추가가 가능합니다. (순차 호출)
Delegate의 선언
public delegate void PrintDelegate(string str);
위 코드에서 PrintDelegate는 string 인자를 받고 반환값이 없는 메서드를 참조할 수 있습니다.
Delegate의 사용
간단하게 Test 클래스를 만들어 내부 Print 함수의 호출이 끝나면 Delegate에 담긴 메서드를 호출해보겠습니다.
// Delegate 선언
public delegate void PrintDelegate(string str);
class Test
{
public void TestPrint(PrintDelegate del)
{
Console.WriteLine("TEST Print");
// del(PrintDelegate)이 참조하는 메서드 호출
del.Invoke("End");
}
}
internal class Program
{
static void Main(string[] args)
{
// 메서드 참조(PrintStr, PrintStr2)
PrintDelegate printDelegate = PrintStr;
printDelegate += PrintStr2;
// Test 인스턴스의 TestPrint()함수 실행
new Test().TestPrint(printDelegate);
}
static public void PrintStr(string arg)
{
Console.WriteLine("Print : " + arg);
}
static public void PrintStr2(string arg)
{
Console.WriteLine("Print2 : " + arg);
}
}
Delegate를 사용하여 위와 같이 특정 상황에서 이벤트를 발생시켜 참조된 메서드들을 호출할 수 있습니다.
728x90
반응형
'Game Programming > C#' 카테고리의 다른 글
[C#] 얕은 복사 vs 깊은 복사 (Shallow Copy vs Deep Copy) (0) | 2024.06.29 |
---|---|
[C#] 의존성 주입(DI, Dependency Injection) (0) | 2024.06.29 |
[C#] as, is (0) | 2024.06.25 |
[C#] 가변 파라미터, 선택적 인수, 명명된 인수 (0) | 2024.06.25 |
[C#] Null 조건 연산자 (0) | 2024.06.25 |