C#内置委托

时间:2021-07-30 06:35:17

namespace ConsoleApplication2

{

    static class Extend

    {

        public static TSource First2<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)

        {

            //.Net本身的源代码好多异常情况处理,好多设计模式,,我也不懂,只提取逻辑

            foreach (TSource item in source)

            {

                if (predicate(item))

                {

                    return (item);

                }

            }

            throw new Exception("不存在满足条件的第一个元素!");

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            List<int> ListInt = new List<int>(){ 1, 2, 3, 4, 5 };

            int k = ListInt.First2(m => m > 4);     //输出5

            Console.WriteLine(k);

 

            Console.ReadKey();

        }

    }