Predicate 대리자 사용하기

    Predicate<T> 대리자는 T를 매개변수로 받아 어떤 로직을 수행한 후 그 결과를 bool 형식으로 반환하는 메서드를 대신 호출합니다.

    > Predicate<string> isNullOrEmpty = String.IsNullOrEmpty;
    > isNullOrEmpty("Not Null")
    false
    > Predicate<Type> isPrimitive = t => t.IsPrimitive;
    > isPrimitive(typeof(int))
    true

     

    Predicate 제네릭 대리자를 메서드의 매개변수로 사용하기

    매개변수에 Func<T>, Action<T>, Predicate<T> 형식을 지정한 메서드는 람다 식을 매개변수로 받을 수 있습니다. 다음 내용을 입력한 후 실행해 보세요. FindNumbers() 함수는 1부터 100까지 정수 중에서 33의 배수를 구합니다.

    > static IEnumerable<int> FindNumbers(Predicate<int> predicate)
    . {
    .     for (int i = 1; i <= 100; i++)
    .     {
    .         if (predicate(i))
    .         {
    .             yield return i;
    .         }
    .     }
    . }
    > var numbers = FindNumbers(f => f % 33 == 0);
    > numbers
    FindNumbers { 33, 66, 99 }
    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.