Predicate委托

泛型委托:表示定义一组条件并确定指定对象是否符合这些条件的方法。此委托由 Array 和 List 类的几种方法使用,用于在集合中搜索元素。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace PredicateTest
{
    public class Point
    {
        public int X { get; set; }
        public int Y { get; set; }
        public Point(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Point[] points = {new Point(150, 250), 
            new Point(200, 200), new Point(250, 375), 
            new Point(275, 395), new Point(295, 450)};
            Point first = Array.Find(points, ProductGT10);//找到符合的数据立马返回, 即使后面有符合条件的数据
            Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
            Console.ReadLine();
        }

        private static bool ProductGT10(Point p)
        {
            if (p.X + p.Y == 400)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

使用带有 Array.Find 方法的 Predicate 委托搜索 Point 结构的数组。如果 X 和 Y 字段的乘积大于 100,000,此委托表示的方法 ProductGT10 将返回 true。Find 方法为数组的每个元素调用此委托,在符合测试条件的第一个点处停止。

猜你喜欢

转载自www.cnblogs.com/LuckyZLi/p/12888752.html