일반
C# Delegate
알 수 없는 사용자
2022. 3. 4. 11:53
SMALL
C# delegate의 개념
C# delegate는 C/C++의 함수 포인터와 비슷한 개념으로 메서드 파라미터와 리턴 타입에 대한 정의를 한 후
동일한 파라미터와 리턴 타입을 가진 메서드를 서로 호환해서 불러쓸수 있는 기능이다.
델리게이트는 한마디로 말해서 대리자라고 말한다
즉, 대신 일을 해주는 녀석이다
다른 말로 해서는 메소드 참조를 포함하고 있는 영역이라고 말할 수 있다
아래는 델리게이트의 선언 형식
delegate 반환형 델리게이트명(매개변수..);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication39
{
delegate int PDelegate(int a, int b);
class Program
{
static int Plus(int a, int b)
{
return a + b;
}
static void Main(string[] args)
{
PDelegate pd1 = Plus;
PDelegate pd2 = delegate(int a, int b)
{
return a / b;
};
Console.WriteLine(pd1(5, 10));
Console.WriteLine(pd2(10, 5));
}
}
}
9행에 PDelegate라는 델리케이트가 있다
매개변수부분에 int형 매개변수 a,b
13~16행에서 Plus메소드
20행을 보면 Plus 메소드 자체를 델리게이트에 집어넣고 있다
Plus 메소드와 연결하여 대리자를 인스턴스화 한다
델리게이트 pd1은 Plus 메소드를 참조한다
참고링크
LIST