Predicate表示定义一组条件并确定指定对象是否符合这些条件的方法。Comparison表示比较同一类型的两个对象的方法。本文主要介绍.NET Framework中自带的泛型委托Predicate和Comparison的使用。
Predicate 相当于 Func和Action类似的委托。表示定义一组条件并确定指定对象是否符合这些条件的方法。Predicate委托通常由 Array 和 List 类的几种方法使用,常用于在集合中搜索元素。
.NET Framework中的定义如下,
public delegate bool Predicate
例如,
- using System;
- using System.Reflection;
- using System.Collections.Generic;
- namespace Predicate
- {
- public struct Point
- {
- public Point(int x,int y)
- {
- this.X = x;
- this.Y = y;
- }
- public int X { get;set;}
- public int Y { get;set;}
- }
- class Program
- {
- static void Main(string[] args)
- {
- Point[] points =
- {
- new Point(100,200),
- new Point(150,250),
- new Point(250,375),
- new Point(275,390),
- new Point(296,400)
- };
- Predicate
predicate = FindPoints; - Point first1 = Array.Find(points, predicate);
- Console.WriteLine("使用FindPoints:");
- Console.WriteLine($"Found:X={first1.X},Y={first1.Y}");
- Point first2 = Array.Find(points, ptn => ptn.X * ptn.Y > 100000);
- Console.WriteLine("使用Lambda:");
- Console.WriteLine($"Found:X={first2.X},Y={first2.Y}");
- Console.ReadKey();
- }
- private static bool FindPoints(Point ptn)
- {
- return ptn.X * ptn.Y > 100000;
- }
- }
- }
Comparison委托由 Array 类的 Sort方法重载和 List 类的 Sort(Comparison 方法重载使用,用于对数组或列表中的元素进行排序。
.NET Framework中的定义如下,
public delegate int Comparison
例如,
- using System;
- class ListSort
- {
- static void Main()
- {
- int[] nums = {3,6,8,1,2,9};
- //使用匿名方法实现 Comparison
- Array.Sort(nums , delegate(int i,int j){
- if (i == j) // 这个接口的返回值为 1 0 -1. 用来实现排序
- { // 这里是倒序排列
- return 0; //相等 返回 0
- }
- else if (i < j)
- {
- return 1;
- }
- else
- return -1;
- });
- foreach(int i in nums)
- Console.Write(i+",");
- Console.WriteLine();
- nums=new int[] {13,16,18,11,12,19};
- //使用lambda实现 Comparison
- Array.Sort(nums , (int i,int j)=>{ //使用匿名方法实现 Comparison
- if (i == j) // 这个接口的返回值为 1 0 -1. 用来实现排序
- { // 这里是倒序排列
- return 0; //相等 返回 0
- }
- else if (i < j)
- {
- return 1;
- }
- else
- return -1;
- });
- foreach(int i in nums)
- Console.Write(i+",");
- Console.WriteLine();
- nums=new int[] {23,26,28,21,22,29};
- //使用定义方法实现 Comparison
- Array.Sort(nums , CompareValue);
- #region output
- foreach(int i in nums)
- Console.Write(i+",");
- Console.WriteLine();
- #endregion
- }
- private static int CompareValue(int i,int j)
- {
- if (i == j) // 这个接口的返回值为 1 0 -1. 用来实现排序
- { // 这里是倒序排列
- return 0; //相等 返回 0
- }
- else if (i < j)
- {
- return 1;
- }
- else
- return -1;
- }
- }