AI智能
改变未来

C#学习.委托实例

  class Program
    {

       //声明委托类型
        delegate bool Function(int num);

      //传入委托

        static Function GreateThan10 = delegate (int num) { return num >= 10; };
        static Function IsEven = delegate (int num) { return num % 2 == 0; };

        static List<int> Traverse(List<int> nums, Function function)//修改形参列表
        {
            var list = new List<int>();
            foreach(var num in nums)
            {
                if(function(num))//修改形参列表
                {
                    list.Add(num);
                }
            }
            return list;
        }
       
        static void Main(string[] args)
        {
//            var list = Traverse(new List<int>() { 1, 3, 6, 11, 21, 7 ,12}, GreateThan10); //传入委托
            var list = Traverse(new List<int>() { 1, 3, 6, 11, 21, 7, 12 }, IsEven); //传入委托
            foreach (var num in list)
            {
                Console.WriteLine(num);
            }
            Console.Read();
        }
    }

 

优化后代码:Lambda

   class Program
    {
        static Func<int, bool> GreatThanTen = delegate (int num) { return num >= 10; };
        static Func<int, bool> IsEven = delegate (int num) { return num % 2 == 0; };

 

//上下两个语句都可以使用
//        static List<int> Traverse(List<int> nums,Func<int,bool> funtion)//系统自带Func<int,bool>接收int,返回bool

       static List<int> Traverse(List<int> nums, Predicate<int> funtion)//Predicate输入参数,返回bool型
        {
            var list = new List<int>();
            foreach(var num in nums)
            {
                if(funtion(num))
                {
                    list.Add(num);
                }
            }
            return list;
        }
        static void Main(string[] args)
        {
            var list = Traverse(new List<int>() { 1, 4, 7, 11, 13, 12, 15 },(num)=> { return num % 2 == 0; });
            foreach(var n in list)
            {
                Console.WriteLine(n);
            }
            Console.Read();
        }
    }

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » C#学习.委托实例