首页 > 代码库 > C#委托,匿名函数,lambda的演变

C#委托,匿名函数,lambda的演变

委托关键词:delegate

委托是把一个方法当成参数进行传递。

先声明一个委托:两个参数,返回bool类型

delegate bool Mydelegate(object obj1,object obj2);

委托所对应的方法:

    static bool CompareNums(object obj1,object obj2)
        {
            return (int)obj1 > (int)obj2;
        }

获取最大值的方法:

 static object GetMax(object[] objs,Mydelegate mydelegate)
        {
            object max = objs[0];
            foreach (var item in objs)
            {
                if (CompareNums(item, max))
                {
                    max = item;
                }
            }
            return max;
       }

调用方法:

        static void Main(string[] args)
        {
            object[] nums = {1,2,3,4,5,0 };
            Mydelegate mydel = new Mydelegate(CompareNums);
            object max = GetMax(nums, mydel);
            Console.WriteLine(max);
            Console.ReadKey();
        }

========由于获取最大值的方法只用到一次,可以使用匿名方法来代替,这样会更简洁=======

        static void Main(string[] args)
        {
            object[] nums = {1,2,3,4,5,0 };
            Mydelegate mydel = delegate (object obj1, object obj2) { return (int)obj1 > (int)obj2; };
            object max = GetMax(nums, mydel);
            Console.WriteLine(max);
            Console.ReadKey();
        }

=================由于系统自带Action和Func两种委托,所以没必要去自定义委托啦=================

Action委托返回值为void

Func有返回值

获取最大值方法改造为:

        static object GetMax(object[] objs,Func<object,object,bool>func)
        {
            object max = objs[0];
            foreach (var item in objs)
            {
                if (CompareNums(item, max))
                {
                    max = item;
                }
            }
            return max;
        }

方法调用改造为:

        static void Main(string[] args)
        {
            object[] nums = {1,2,3,4,5,0 };
            Func<object,object,bool> func= delegate (object obj1, object obj2) { return (int)obj1 > (int)obj2; };
            object max = GetMax(nums, func);
            Console.WriteLine(max);
            Console.ReadKey();
        }

=================使用lambda进行简化====================

        static void Main(string[] args)
        {
            object[] nums = {1,2,3,4,5,0 };
            Func<object, object, bool> func = (obj1, obj2) => { return (int)obj1 > (int)obj2; };
            object max = GetMax(nums, func);
            Console.WriteLine(max);
            Console.ReadKey();
        }

C#委托,匿名函数,lambda的演变