메서드를 참조한다.
다중 메서드 호출이 가능하다.
콜백 함수를 지정하는데 사용된다.
델리게이트는 C#의 이벤트, LINQ(언어 통합 쿼리), 콜백 메커니즘 등에서 널리 사용.
또한 델리게이트는 코드의 유연성과 재사용성을 높이며, 프로그램의 확장성을 향상시키는 데 도움이 된다.
using System;
public delegate void MyDelegate(string message); // 델리게이트 정의
public class DelegateExample {
public void Method1(string message) {
Console.WriteLine("Method 1: " + message);
}
public void Method2(string message) {
Console.WriteLine("Method 2: " + message);
}
}
public class Program {
public static void Main() {
DelegateExample example = new DelegateExample();
MyDelegate del = example.Method1; // 델리게이트에 Method1 추가
del += example.Method2; // 델리게이트에 Method2 추가
// 델리게이트를 호출하여 메서드 실행
del("Hello, delegates!");
// 비동기적 프로그래밍에서 콜백 함수로 사용하는 예시
Action<string> callback = new Action<string>(example.Method1);
SomeAsyncMethod("Hello, async delegates!", callback);
}
public static void SomeAsyncMethod(string message, Action<string> callback) {
// 비동기적 작업 수행
Console.WriteLine("Doing some async work...");
// 작업이 완료된 후 콜백 함수 호출
callback(message);
}
}