Predicate<T> 대리자

정의

조건 집합을 정의하고 지정된 개체가 이러한 조건을 충족하는지 여부를 확인하는 메서드를 나타냅니다.

generic <typename T>
public delegate bool Predicate(T obj);
public delegate bool Predicate<in T>(T obj);
public delegate bool Predicate<T>(T obj);
type Predicate<'T> = delegate of 'T -> bool
Public Delegate Function Predicate(Of In T)(obj As T) As Boolean 
Public Delegate Function Predicate(Of T)(obj As T) As Boolean 

형식 매개 변수

T

비교할 개체의 형식입니다.

이 형식 매개 변수는 반공변(Contravariant)입니다. 즉, 지정한 형식이나 더 적게 파생된 모든 형식을 사용할 수 있습니다. 공변성(Covariance) 및 반공변성(Contravariance)에 대한 자세한 내용은 제네릭의 공변성(Covariance) 및 반공변성(Contravariance)을 참조하세요.

매개 변수

obj
T

이 대리자가 나타내는 메서드에 정의된 조건과 비교할 개체입니다.

반환 값

Boolean

obj가 이 대리자가 나타내는 메서드에 정의된 조건을 충족하면 true이고, 그렇지 않으면 false입니다.

예제

다음 코드 예제에서는 메서드와 대리 Array.Find 자를 Predicate<T> 사용하여 구조체 배열 Point 을 검색합니다. 이 예제에서는 명명된 predicate 대리자를 Predicate<T> 명시적으로 정의하고 필드의 Point.Y Point.X 곱이 100,000보다 큰 경우 반환 true 하는 메서드 FindPoints 를 할당합니다. 두 번째 예제와 같이 형식 Predicate<T>의 대리자를 명시적으로 정의하는 대신 람다 식을 사용하는 것이 관례입니다.

using System;
using System.Drawing;

public class Example
{
   public static void Main()
   {
      // Create an array of Point structures.
      Point[] points = { new Point(100, 200),
                         new Point(150, 250), new Point(250, 375),
                         new Point(275, 395), new Point(295, 450) };

      // Define the Predicate<T> delegate.
      Predicate<Point> predicate = FindPoints;

      // Find the first Point structure for which X times Y
      // is greater than 100000.
      Point first = Array.Find(points, predicate);

      // Display the first structure found.
      Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
   }

   private static bool FindPoints(Point obj)
   {
      return obj.X * obj.Y > 100000;
   }
}
// The example displays the following output:
//        Found: X = 275, Y = 395
open System
open System.Drawing

let findPoints (obj: Point) =
    obj.X * obj.Y > 100000

// Create an array of Point structures.
let points = 
    [| Point(100, 200)
       Point(150, 250) 
       Point(250, 375)
       Point(275, 395) 
       Point(295, 450) |]

// Define the Predicate<T> delegate.
let predicate = Predicate<Point> findPoints

// Find the first Point structure for which X times Y
// is greater than 100000.
let first = Array.Find(points, predicate)

// Display the first structure found.
printfn $"Found: X = {first.X}, Y = {first.Y}"
// The example displays the following output:
//        Found: X = 275, Y = 395
Imports System.Drawing

Public Class Example
   Public Shared Sub Main()

      ' Create an array of Point structures. 
      Dim points() As Point = { new Point(100, 200), new Point(150, 250), 
                                new Point(250, 375), new Point(275, 395), 
                                new Point(295, 450) }
      
      ' Define the Predicate(Of T) delegate.
      Dim predicate As Predicate(Of Point) = AddressOf Example.FindPoints
      
      ' Find the first Point structure for which X times Y  
      ' is greater than 100000. 
      Dim first As Point = Array.Find(points, predicate)

      ' Display the first structure found.
      Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y)
   End Sub 
   
   Private Shared Function FindPoints(obj As Point) As Boolean
      Return obj.X * obj.Y > 100000
   End Function

End Class 
' The example displays the following output:
'       Found: X = 275, Y = 395

다음 예제는 대리자를 나타내는 람다 식을 사용한다는 점을 제외하고 이전 예제와 Predicate<T> 동일합니다. 식이 points 검색 조건을 충족하는 요소를 발견할 때까지 배열의 각 요소가 람다 식에 전달됩니다. 이 경우 X 및 Y 필드의 곱이 100,000보다 큰 경우 람다 식이 반환 true 됩니다.

using System;
using System.Drawing;

public class Example
{
   public static void Main()
   {
      // Create an array of Point structures.
      Point[] points = { new Point(100, 200),
                         new Point(150, 250), new Point(250, 375),
                         new Point(275, 395), new Point(295, 450) };

      // Find the first Point structure for which X times Y
      // is greater than 100000.
      Point first = Array.Find(points, x => x.X * x.Y > 100000 );

      // Display the first structure found.
      Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
   }
}
// The example displays the following output:
//        Found: X = 275, Y = 395
open System
open System.Drawing

// Create an array of Point structures.
let points = 
    [| Point(100, 200)
       Point(150, 250)
       Point(250, 375)
       Point(275, 395)
       Point(295, 450) |]

// Find the first Point structure for which X times Y
// is greater than 100000.
let first = Array.Find(points, fun x -> x.X * x.Y > 100000)

// Display the first structure found.
printfn $"Found: X = {first.X}, Y = {first.Y}"
// The example displays the following output:
//        Found: X = 275, Y = 395
Imports System.Drawing

Public Class Example
   Public Shared Sub Main()

      ' Create an array of Point structures. 
      Dim points() As Point = { new Point(100, 200), new Point(150, 250), 
                                new Point(250, 375), new Point(275, 395), 
                                new Point(295, 450) }

      ' Find the first Point structure for which X times Y  
      ' is greater than 100000. 
      Dim first As Point = Array.Find(points, 
                                 Function(x) x.X * x.Y > 100000 )

      ' Display the first structure found.
      Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y)
   End Sub 
End Class 
' The example displays the following output:
'       Found: X = 275, Y = 395

설명

이 대리자는 컬렉션의 Array 요소를 검색하기 위해 여러 메서드 및 List<T> 클래스에서 사용됩니다.

일반적으로 대리자는 Predicate<T> 람다 식으로 표시됩니다. 로컬로 범위가 지정된 변수를 람다 식에 사용할 수 있으므로 컴파일 시간에 정확하게 알려지지 않은 조건을 쉽게 테스트할 수 있습니다. 이는 다음 예제에서 시뮬레이션됩니다. 이 예제에서는 내셔널 하키 리그 팀과 해당 팀이 설립된 연도에 대한 정보가 포함된 클래스를 정의 HockeyTeam 합니다. 이 예제에서는 연도를 나타내는 정수 값의 배열을 정의하고 배열의 한 요소를 임의로 foundedBeforeYear할당합니다. 이 요소는 예제의 Main 메서드로 로컬로 범위가 지정된 변수입니다. 로컬로 범위가 지정된 변수는 람다 식에 사용할 수 있으므로 메서드에 List<T>.FindAll 전달된 람다 식은 해당 연도 또는 그 이전에 설립된 각 팀의 개체를 반환 HockeyTeam 할 수 있습니다.

using System;
using System.Collections.Generic;

public class HockeyTeam
{
   private string _name;
   private int _founded;

   public HockeyTeam(string name, int year)
   {
      _name = name;
      _founded = year;
   }

   public string Name {
      get { return _name; }
   }

   public int Founded {
      get { return _founded; }
   }
}

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      List<HockeyTeam> teams = new List<HockeyTeam>();
      teams.AddRange( new HockeyTeam[] { new HockeyTeam("Detroit Red Wings", 1926),
                                         new HockeyTeam("Chicago Blackhawks", 1926),
                                         new HockeyTeam("San Jose Sharks", 1991),
                                         new HockeyTeam("Montreal Canadiens", 1909),
                                         new HockeyTeam("St. Louis Blues", 1967) } );
      int[] years = { 1920, 1930, 1980, 2000 };
      int foundedBeforeYear = years[rnd.Next(0, years.Length)];
      Console.WriteLine("Teams founded before {0}:", foundedBeforeYear);
      foreach (var team in teams.FindAll( x => x.Founded <= foundedBeforeYear))
         Console.WriteLine("{0}: {1}", team.Name, team.Founded);
   }
}
// The example displays output similar to the following:
//       Teams founded before 1930:
//       Detroit Red Wings: 1926
//       Chicago Blackhawks: 1926
//       Montreal Canadiens: 1909
open System

type HockeyTeam =
    { Name: string
      Founded: int }

let rnd = Random()
let teams = ResizeArray()
teams.AddRange 
    [| { Name = "Detroit Red Wings"; Founded = 1926 }
       { Name = "Chicago Blackhawks"; Founded = 1926 }
       { Name = "San Jose Sharks"; Founded = 1991 }
       { Name = "Montreal Canadiens"; Founded = 1909 }
       { Name = "St. Louis Blues"; Founded = 1967 }|]

let years = [| 1920; 1930; 1980; 2000 |]
let foundedBeforeYear = years[rnd.Next(0, years.Length)]
printfn $"Teams founded before {foundedBeforeYear}:"
for team in teams.FindAll(fun x -> x.Founded <= foundedBeforeYear) do
    printfn $"{team.Name}: {team.Founded}"
// The example displays output similar to the following:
//       Teams founded before 1930:
//       Detroit Red Wings: 1926
//       Chicago Blackhawks: 1926
//       Montreal Canadiens: 1909
Imports System.Collections.Generic

Public Class HockeyTeam
   Private _name As String
   Private _founded As Integer
   
   Public Sub New(name As String, year As Integer)
      _name = name
      _founded = year
   End Sub

   Public ReadOnly Property Name As String
      Get
         Return _name
      End Get
   End Property

   Public ReadOnly Property Founded As Integer
      Get 
         Return _founded
      End Get   
   End Property
End Class

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim teams As New List(Of HockeyTeam)()
      teams.AddRange( { new HockeyTeam("Detroit Red Wings", 1926), 
                        new HockeyTeam("Chicago Blackhawks", 1926),
                        new HockeyTeam("San Jose Sharks", 1991),
                        new HockeyTeam("Montreal Canadiens", 1909),
                        new HockeyTeam("St. Louis Blues", 1967) } )
      Dim years() As Integer = { 1920, 1930, 1980, 2000 }
      Dim foundedBeforeYear As Integer = years(rnd.Next(0, years.Length))
      Console.WriteLine("Teams founded before {0}:", foundedBeforeYear)
      For Each team in teams.FindAll( Function(x) x.Founded <= foundedBeforeYear )
         Console.WriteLine("{0}: {1}", team.Name, team.Founded)
      Next   
   End Sub
End Module
' The example displays output similar to the following:
'       Teams founded before 1930:
'       Detroit Red Wings: 1926
'       Chicago Blackhawks: 1926
'       Montreal Canadiens: 1909

확장 메서드

GetMethodInfo(Delegate)

지정된 대리자가 나타내는 메서드를 나타내는 개체를 가져옵니다.

적용 대상

추가 정보