반응형
Predicate <T>는 Func나 Action과 같은 미리 정의된 델리게이트 형식이다.
Predicate 델리게이트 메서드는 하나의 매개변수를 갖고 리턴 갑시 bool인 델리게이트다.
Predicate<int> isEven = ISEven;
static bool IsEven(int n)
{
return n % 2 ==0;
}
Predicate <int> isEven은 매개변수가 정수 하나이며, 리턴 값이 bool인 IsEvnen 메서드 이름을 지정한다.
여기서 Predicate isEven는 소문자로 시작하고 메서드 IsEven은 대문자로 시작하는 것을 주의한다.
Predicate로 다음과 같이 IsEven() 메서드를 호출할 수 있다.
Console.WriteLine(isEven(6)); //결과 true
IsEven(int n) 메서드를 람다식으로 변형하면 다음과 같이 가능하다
static bool IsEven(int n) => n % 2 == 0;
IsEven() 메서드를 익명 델리게이트로 쓴다면 Predicate 선언 부분에 직접 쓸 수 있다.
Predicate<int> isEven = n => n % 2 ==0;
코드를 보자 간단하다.
using System;
namespace A118_Predicate
{
class Program
{
static void Main(string[] args)
{
Predicate<int> isEvne = n => n % 2 == 0;
Console.WriteLine(isEvne(6)); //isEven을 람다로 정의 정수하나 보내 bool 리턴
Predicate<string> isLowerCase = s => s.Equals(s.ToLower());
Console.WriteLine(isLowerCase("This is test")); //isLowerCase는 string s를 매개변수로 보냄
}
}
}
'C# 이것저것 > 초보자를 위한 C#200제' 카테고리의 다른 글
[C#] Winform 콤보박스를 이용한 학점계산기 만들기 (0) | 2024.04.09 |
---|---|
[C#] LINQ 기초 (0) | 2024.02.02 |
[C#] 람다식(Lambda Expression) (0) | 2024.02.01 |
[C#] 델리게이트의 기본 (0) | 2024.02.01 |