[C#] 델리게이트(delegate) - Func, Action, Predicate
c#에서는 delegate(대리자)를 사용하여 메서드를 매개변수로 전달하는 방법이 3가지가 있다.
- Func
- Action
- Predicate
Func형 델리게이트
- 입력 매개 변수와 반환 값이 존재한다.
- 입력 매개변수는 필수는 아니다.
- 입력 매개변수의 개수가 16개를 초과하는 경우 컴파일 에러가 발생한다.
.Net 6에서는 아래와 같이 정의되어 있다.
public delegate 반환타입 Func<in 매개변수타입,out 반환타입>(매개변수타입 arg);
https://jjomnoon-diary.tistory.com/28
[C#] 델리게이트(delegate) - 델리게이트, 콜백 사용 방법 및 사용 이유
델리게이트란? 대리자 라는 뜻으로 c++의 함수 포인터와 비슷한 개념을 가지고 있다. 포인터의 설명은 위와 같다고 보면된다. 솔직히 정말 잘 정리한듯,,, 함수 포인터는 함수식을 인스턴스의 포
jjomnoon-diary.tistory.com
의 델리게이트 샘플 코드 에서 Func형으로 수정을 해보자
함수형(Func) 델리게이트 샘플 코드
매서드 참조 함수형 델리게이트(매개변수 O, 반환 값 O)
using System;
namespace MyApp // Note: actual namespace depends on the project name.
{
internal class Program
{
public string DelegateTestA(string msg)//함수형 델리게이트는 리턴값을 가진다.
{
return "Call DelegateTestA, param is " + msg;
}
public string DelegateTestB(string msg)
{
return "Call DelegateTestB, param is " + msg;
}
public Program()
{
Func<string, string> funcDelegateA = DelegateTestA;//함수형 델리게이트 선언
Func<string, string> funcDelegateB = DelegateTestB;
Console.WriteLine(funcDelegateA("A"));//함수형 델리게이트 호출
Console.WriteLine(funcDelegateB("B"));
}
static void Main(string[] args)
{
new Program();
}
}
}
19번째 줄 Func<string, string> funcDelegateA = DelegateTestA; 를 보면 Func의 첫번째 인수가 DelegateTestA의 매개변수로 들어가고, 마지막 인수는 DelegateTestA의 반환 값이다.
매서드 참조 함수형 델리게이트(매개변수 X, 반환 값 O)
using System;
namespace MyApp // Note: actual namespace depends on the project name.
{
internal class Program
{
public string DelegateTestA()
{
return "Call DelegateTestA, param is A";
}
public string DelegateTestB()
{
return "Call DelegateTestB, param is B";
}
public Program()
{
Func<string> funcDelegateA = DelegateTestA;
Func<string> funcDelegateB = DelegateTestB;
Console.WriteLine(funcDelegateA());
Console.WriteLine(funcDelegateB());
}
static void Main(string[] args)
{
new Program();
}
}
}
위의 소스코드를 보면 Func<String>은 out의 string이다.
이를 통해 함수형 델리게이트는 매개변수는 없이 만들 수 있지만, 반환값이 없는 경우는(void) 만들 수는 없다는 것을 뜻한다.
매서드를 매개변수로 전달하는 함수형 델리게이트(매개변수 O, 반환 값 O)
using System;
namespace MyApp // Note: actual namespace depends on the project name.
{
internal class Program
{
public string DelegateTestA(string msg)
{
return "Call DelegateTestA, param is " + msg;
}
public string DelegateTestB(string msg)
{
return "Call DelegateTestB, param is " + msg;
}
public void PrintFunc(Func<string, string> func, string msg)
{
Console.WriteLine(func(msg));
}
public Program()
{
PrintFunc(DelegateTestA, "A");
PrintFunc(DelegateTestB, "B");
}
static void Main(string[] args)
{
new Program();
}
}
}
Action형 델리게이트
반환값이 없는 로직을 처리할 때 사용
Func형과의 차이점
- Action형의 변수를 정의하고 있다.
- 반환값이 없다.
- 입력 매개변수의 개수가 16개를 초과하는 경우 컴파일 에러가 발생한다.
위의 샘플 코드 에서 Action형으로 수정을 해보자
액션형(Action) 델리게이트 샘플 코드
using System;
namespace MyApp // Note: actual namespace depends on the project name.
{
internal class Program
{
public void DelegateTestA(string msg)
{
Console.WriteLine("Call DelegateTestA, param is " + msg);
}
public void DelegateTestB(string msg)
{
Console.WriteLine("Call DelegateTestB, param is " + msg);
}
public void PrintFunc(Action<string> Func, string msg)
{
Func(msg);
}
public Program()
{
PrintFunc(DelegateTestA, "A");
PrintFunc(DelegateTestB, "B");
}
static void Main(string[] args)
{
new Program();
}
}
}
반환값이 없다는것을 제외하고는 Func형 델리게이트와 유사하다.
Predicate 형 델리게이트
Action, Func과 유사하지만 반환타입이 bool이고, 입력 매개변수의 개수가 무조건 하나인 경우 사용할 수 있다.
- Func형 델리게이트와 다르게 반환타입(out)을 명시하지 않는다.
Predicate 델리게이트 샘플 코드
using System;
namespace ConsoleApp1
{
internal class DelegatePredicate
{
public static bool IsAdult(int age)
{
if (age > 19)
return true;
else
return false;
}
public void PrintFunc(Predicate<int> func, int age)
{
if (func(age))
Console.WriteLine("성인");
else
Console.WriteLine("미성년자");
}
public DelegatePredicate()
{
PrintFunc(IsAdult, 30);
PrintFunc(IsAdult, 10);
}
static void Main(string[] args)
{
new DelegatePredicate();
}
}
}
※정리※
매개변수 O, 반환값 O
delegate
delegate 반환타입 함수명(매개변수);
Func
Func<입력 매개변수(in),.. (최대 16개), 반환타입(out)> 함수명;
Predicate
Predicate<입력 매개변수> 함수명;//반환 타입은 항상 bool
매개변수 X, 반환값 O
delegate
delegate 반환타입 함수명();
Func
Func<반환타입> 함수명;
매개변수 O, 반환값 X
delegate
delegate void 함수명(매개변수);
Action
Action<입력 매개변수, ..(최대 16개)> 함수명;
매개변수 X, 반환값 X
delegate
delegate void 함수명();
Action
Action 함수명;
포스팅에 오류가 있거나 오타가 있다면 댓글로 알려주시기 바랍니다.
도움이 되셨다면 공감버튼을 눌러주세요.🥰