닷넷(.NET)에서는 일반적인 사용 사례를 위해 Func<> 및 Action<>과 같은 제네릭 빌트인 대리자를 제공한다
Func<>는 반환 값이 있는 메서드를 위한 대리자이며, Action<>은 반환 값이 없는 메서드를 위한 대리자이다.
Action<> 대리자는 0개에서 16개까지의 매개변수를 가질 수 있다. (Action, Action, Action<T1, T2>, ..., Action<T1, T2, ..., T16>).
Action<string> => 문자열을 매개변수로 받고 반환 값이 없는 메서드.
Func<>는 0개에서 16개까지의 입력 매개변수와 하나의 반환 값을 가질 수 있다, (Func, Func<T, TResult>, Func<T1, T2, TResult>, ..., Func<T1, T2, ..., T16, TResult>).
Func<>의 마지막 파지막 파라미터는(TResult) Return 반환형식을 의미한다.
Func<int, int, bool>이 있다면 bool이 반환 형식
참고로 대리자도 참조 형식이지만 선언할 때 new를 생략해도 된다.
using System;
public class DelegateExample
{
public delegate void MyDelegate(string message);
public void DisplayMessage(string message)
{
Console.WriteLine(message);
}
public void Execute()
{
MyDelegate del = DisplayMessage;
del("Hello, World!");
}
static void Main()
{
var example = new DelegateExample();
example.Execute();
}
}
internal class Program
{
static void Main(string[] args)
{
// 예제
List<int> numbers = new List<int> { 8, 4, 1, 3, 5, 2, 7, 6 };
// 비교함수
// Func 대리자 사용.
Func<int, int, bool> lessThan = LessThan;
// 출력 함수
// Action 대리자 사용.
Action<List<int>> printList = PrintList;
Console.WriteLine("Before sorting:");
printList(numbers);
SortList(numbers, lessThan);
// 정렬 후 리스트 출력
Console.WriteLine("After sorting:");
printList(numbers);
}
public static bool LessThan(int a, int b)
{
return a < b;
}
// 리스트 출력 함수 구현
public static void PrintList(List<int> list)
{
foreach (var item in list)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
// 메서드의 아규먼트에 함수 선언.
// compareFunc 대리자 사용.
public static void SortList<T>(List<T> list, Func<T, T, bool> compareFunc)
{
for (int i = 0; i < list.Count - 1; i++)
{
int minIndex = i;
for (int j = i + 1; j < list.Count; j++)
{
if (compareFunc(list[j], list[minIndex]))
{
minIndex = j;
}
}
// 요소 교환
T temp = list[i];
list[i] = list[minIndex];
list[minIndex] = temp;
}
}
}