English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# Predicate 대리자

Predicate는 Func와 Action이 대표하는 것과 같은 대리자입니다. 특정 객체가 지정된 조건을 만족하는지 결정하는 메서드를 정의합니다. 이 대리자는 Array와 List 클래스의 여러 메서드에서 사용되어 집합에서 요소를 검색하는 데 사용됩니다. Predicate 대리자 메서드는 입력 매개변수를 받아야 하며 true 또는 false 값을 반환해야 합니다.

Predicate 대리자 정의

Predicate 대리자는 System에서 정의된 네임스페이스에 있습니다. 예를 들어:

Predicate 서명:

public delegate bool Predicate<in T>(T obj);

기타 대리자 타입과 마찬가지로, Predicate 대리자는 어떤 메서드, 익명 메서드 또는 람다 표현식과도 함께 사용될 수 있습니다.

static bool IsUpperCase(string str)
{
    return str.Equals(str.ToUpper());
bool result = isUpper("hello world!!");
static void Main(string[] args)
{
    Predicate<string> isUpper = IsUpperCase;
    bool result = isUpper("hello world!!");
    Console.WriteLine(result);
bool result = isUpper("hello world!!");
출력:
false

Predicate 대리자와 익명 메서드

익명 메서드를 Predicate 대리자 타입에 할당할 수도 있습니다. 예를 들어:

static void Main(string[] args)
{
    Predicate<string> isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
    bool result = isUpper("hello world!!");
bool result = isUpper("hello world!!");

Predicate 대리자와 람다 표현식

람다 표현식을 Predicate 대리자 타입에 할당할 수도 있습니다. 예를 들어:

static void Main(string[] args)
{
    Predicate<string> isUpper = s => s.Equals(s.ToUpper());
    bool result = isUpper("hello world!!");
bool result = isUpper("hello world!!");

}

  • Predicate 대리자 사용 설명

  • Predicate 대리자는 bool 타입의 return type을 가진 generic 대리자입니다.

  • Predicate<int> 대리자는 입력 매개변수가 int 타입이고 bool 값을 반환하는 대리자입니다.

Predicate 대리자는 하나의 매개변수를 가지고 fixed로 bool 값을 반환합니다.

  1. 기억해야 할 주요 사항

  2. predicate 대리자는 입력 매개변수 하나와 부울 값을 반환하는 타입을 가집니다.