C#/C#200제
[C#] 16일차 - 115. Func와 Action으로 델리게이트를 더 간단히 만들기
반나무
2021. 2. 14. 13:42
Func 델리게이트는 결과를 반환하는 메소드를 참조하기위해
Action 델리게이트는 결과를 반환하지 않는 메소드를 참조하기위해 사용된다.
거의 모든 델리게이트를 Func와 Action으로 쓸 수 있다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace A115_FuncAndAction
{
class Program
{
// delegate bool MemberTest(int x); Func를 사용하므로 필요없어짐
static void Main(string[] args)
{
var arr = new[] { 3, 34, 6, 34, 7, 8, 24, 3, 675, 8, 23 };
int n = Count(arr, delegate (int x) { return x % 2 == 0; });
Console.WriteLine("짝수의 개수 : {0}", n);
n = Count(arr, delegate (int x) { return x % 2 != 0; });
Console.WriteLine("홀수의 개수 : {0}", n);
}
private static int Count(int[] arr, Func<int, bool> testMethod)
{
int cnt = 0;
foreach(var n in arr)
{
if (testMethod(n))
cnt++;
}
return cnt;
}
}
}
반응형