안녕하세요! 이번 포스팅에서는 C#의 중요한 개념 중 하나인 **델리게이트(Delegate)**에 대해 자세히 알아보겠습니다. 델리게이트를 이해하면 C#에서 콜백 함수, 이벤트 처리, 메서드 참조 등의 기능을 효과적으로 활용할 수 있습니다. 😊
델리게이트(Delegate)란?
델리게이트(Delegate)는 메서드를 가리키는 포인터와 유사한 기능을 하는 참조 타입입니다. 즉, 특정 메서드를 대신 호출할 수 있는 변수 역할을 합니다. 이를 통해 메서드를 변수처럼 저장하고 실행할 수 있습니다.
델리게이트 선언 및 사용
delegate void PrintMessage(string message);
class Program
{
static void Print(string message)
{
Console.WriteLine(message);
}
static void Main()
{
PrintMessage printer = new PrintMessage(Print);
printer("Hello, Delegate!");
}
}
출력 결과:
Hello, Delegate!
익명 메서드(Anonymous Method) 사용하기
C#에서는 delegate 키워드를 사용하여 익명 메서드를 생성할 수도 있습니다.
PrintMessage printer = delegate(string message)
{
Console.WriteLine("익명 메서드: " + message);
};
printer("안녕하세요!");
출력 결과:
익명 메서드: 안녕하세요!
람다식(Lambda Expression)과 델리게이트
람다식(Lambda Expression)을 사용하면 더욱 간결한 코드 작성이 가능합니다.
PrintMessage printer = message => Console.WriteLine("람다식: " + message);
printer("Hello Lambda!");
출력 결과:
람다식: Hello Lambda!
델리게이트 체인(멀티캐스트 델리게이트)
하나의 델리게이트에 여러 개의 메서드를 연결할 수도 있습니다.
delegate void Notify();
class Program
{
static void Method1() { Console.WriteLine("Method1 실행"); }
static void Method2() { Console.WriteLine("Method2 실행"); }
static void Main()
{
Notify notify = Method1;
notify += Method2;
notify(); // Method1, Method2 순차 실행
}
}
출력 결과:
Method1 실행
Method2 실행
델리게이트와 Func, Action, Predicate
C#에서는 기본 제공되는 델리게이트 타입이 있습니다.
1. Func<T> : 반환값이 있는 델리게이트
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(3, 5)); // 8
2. Action<T> : 반환값이 없는 델리게이트
Action<string> showMessage = message => Console.WriteLine(message);
showMessage("Hello Action!");
3. Predicate<T> : bool을 반환하는 델리게이트
Predicate<int> isEven = num => num % 2 == 0;
Console.WriteLine(isEven(4)); // True
델리게이트를 활용한 이벤트(Event) 처리
델리게이트는 이벤트(Event) 처리에서도 중요한 역할을 합니다. 이벤트는 특정 동작이 발생했을 때 실행할 메서드를 연결하는 방식으로 구현됩니다.
이벤트와 델리게이트 사용 예제
using System;
class Button
{
public delegate void ClickEventHandler();
public event ClickEventHandler Click;
public void OnClick()
{
if (Click != null)
Click();
}
}
class Program
{
static void Main()
{
Button button = new Button();
button.Click += () => Console.WriteLine("버튼이 클릭되었습니다!");
button.OnClick();
}
}
출력 결과:
버튼이 클릭되었습니다!
결론
이번 포스팅에서는 C#의 **델리게이트(Delegate)**에 대해 알아보았습니다. 델리게이트는 메서드를 변수처럼 다룰 수 있도록 해주는 강력한 기능으로, 다음과 같은 활용이 가능합니다.
✅ 특정 메서드를 참조하여 실행할 수 있음 ✅ 익명 메서드 및 람다식을 사용하여 간결한 코드 작성 가능 ✅ 여러 개의 메서드를 동시에 실행하는 델리게이트 체인 ✅ Func, Action, Predicate를 활용한 다양한 기능 제공 ✅ 이벤트(Event) 처리에 필수적인 요소
이제 델리게이트를 활용하여 더 깔끔하고 유연한 C# 코드를 작성해 보세요! 도움이 되셨다면 댓글과 좋아요 부탁드립니다. 😊