Predicate<T> 代理人

定義

表示定義一組準則的方法,並判斷指定的物件是否符合這些準則。Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.

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

類型參數

T

要比較之物件的型別。The type of the object to compare.

參數

obj

要比較的物件,根據這個委派表示方法中所定義的準則。The object to compare against the criteria defined within the method represented by this delegate.

傳回值

Boolean

如果 obj 符合這個委派表示方法中所定義的準則,則為 true,否則為 falsetrue if obj meets the criteria defined within the method represented by this delegate; otherwise, false.

繼承
Predicate<T>

範例

下列程式碼範例會使用Predicate<T> Array.Find具有方法的委派, 來搜尋結構的Point陣列。The following code example uses a Predicate<T> delegate with the Array.Find method to search an array of Point structures. 此範例會明確定義Predicate<T>名為predicate的委派, 並為它FindPoints指派true一個名為的方法, Point.X如果Point.Y和欄位的乘積大於 100000, 則會傳回。The example explicitly defines a Predicate<T> delegate named predicate and assigns it a method named FindPoints that returns true if the product of the Point.X and Point.Y fields is greater than 100,000. 請注意, 您可以使用 lambda 運算式, 而不是明確定義類型Predicate<T>的委派, 如同第二個範例所示。Note that it is customary to use a lambda expression rather than to explicitly define a delegate of type Predicate<T>, as the second example illustrates.

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
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

下列範例與前一個範例相同, 不同之處在于它會使用 lambda 運算式來代表Predicate<T>委派。The following example is identical to the previous example, except that it uses a lambda expression to represent the Predicate<T> delegate. points陣列的每個元素都會傳遞至 lambda 運算式, 直到運算式找到符合搜尋準則的專案為止。Each element of the points array is passed to the lambda expression until the expression finds an element that meets the search criteria. 在此情況下, true如果 X 和 Y 欄位的乘積大於 100000, 則 lambda 運算式會傳回。In this case, the lambda expression returns true if the product of the X and Y fields is greater than 100,000.

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
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

備註

ArrayList<T>類別的數個方法會使用這個委派來搜尋集合中的元素。This delegate is used by several methods of the Array and List<T> classes to search for elements in the collection.

通常, Predicate<T>委派是以 lambda 運算式來表示。Typically, the Predicate<T> delegate is represented by a lambda expression. 因為本機範圍的變數可用於 lambda 運算式, 所以很容易就能在編譯時期測試不知道的條件。Because locally scoped variables are available to the lambda expression, it is easy to test for a condition that is not precisely known at compile time. 這會在下列範例中模擬, 這會定義HockeyTeam一個類別, 其中包含全國 Hockey 聯盟小組和其成立年份的相關資訊。This is simulated in the following example, which defines a HockeyTeam class that contains information about a National Hockey League team and the year in which it was founded. 這個範例會定義代表年份的整數值陣列, 並隨機將陣列的一個元素指派給foundedBeforeYear, 這是在本機範圍設定為Main範例方法的變數。The example defines an array of integer values that represent years, and randomly assigns one element of the array to foundedBeforeYear, which is a variable that is locally scoped to the example's Main method. 因為本機範圍的變數可用於 lambda 運算式, 所以傳遞至List<T>.FindAll方法的 lambda 運算式可以HockeyTeam針對在該年份之前或之前的每個小組傳回物件。Because locally scoped variables are available to a lambda expression, the lambda expression passed to the List<T>.FindAll method is able to return a HockeyTeam object for each team founded on or before that year.

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
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)

取得表示特定委派所代表之方法的物件。Gets an object that represents the method represented by the specified delegate.

適用於

另請參閱