Action, Func, Predicate

박지예·2023년 11월 8일
0

공부

목록 보기
36/42

기본 지식 : 델리게이트

델리게이트 : 함수를 변수처럼 사용하는 것. 변수에 함수를 담을 수 있다!

Action, Func, Predicate는 명시적으로 델리게이트를 선언할 필요 없이 델리게이트의 장점을 누릴 수 있다.

1. Action

기존 델리게이트 코드

delegate void TestDelegate();

static void Main(string[] args)
{
		TestDelegate testDel = () => Console.WriteLine("Test");
}

Action 사용

static void Main(string[] args)
{
		Action testAction = () => Console.WriteLine("Test");
}

Action 이라는 델리게이트는 리턴 값이 없을 때만 사용 가능하다.

매개변수를 받을 수 도 있다. <> 꺽새를 사용해서 매개변수 타입을 적어줘야 한다.

static void Main(string[] args)
{
		Action<string> testAction = (string value) => Console.WriteLine("Test");
}

그러면 반환 값이 있는 함수를 사용하려면 어떻게 해야할까?

2. Func

static void Main(string[] args)
{
		Func<string,string> testAction = (string value) => value;

		Func<int,int ,int> HapAction = (int num1, int num2) => num1 + num2;
}

Func는 꺽새 안에 두개 이상의 값이 들어간다.

마지막 값은 리턴 값을 의미하고, 그 앞 값들은 파라미터의 타입을 의미한다.

3. Predicate

마지막으로 Predicate는 무조건 Boolean의 형태를 반환한다.

리턴 타입은 정해졌으니까 명시할 필요가 없다. 즉, 매개변수 타입 1개만 명시해주면 된다.

static void Main(string[] args)
{
		Predicate<int> test = (num) => num > 5;
}
profile
언젠간 바다로 갈거야!🐋

0개의 댓글