.Net delegate和Action以及Func委托的使用Demo

.

class Program
    {
        static void Main(string[] args)
        {
           //原始委托
            F1 f = Show;
               f+= Show2;
            f();


            Console.WriteLine();

            //匿名委托
            //Action无返回值委托
            Action action = delegate (string name, int number)
            {
                Console.WriteLine($"{name},{number}");
            };
            action("张三",8);

            //Action有返回值委托
            Func func = delegate ( int number)
            {
                return 0 + number;
            };
            Console.WriteLine(func(8));

            //lambda加持

            //Action无返回值委托
            Action action2 =  (name,number)=> Console.WriteLine($"{name},{number}");
            action2("张三", 8);

            //Action有返回值委托
            Func func2 =   number=> 0 + number;
            Console.WriteLine(func(8));

            //原始和匿名加lambda委托
            Func func3 = i => i > 5;
            func3(0);

            F3 f3 = isV;
            f3(0);

            Func fun3 = delegate (int i)
            {
                return i > 5; 
            };
            fun3(0);


            //找值

            //方法一
            int[] number = new int[] { 55, 33, 66, 88, 24, 64, 18, 94 };
            IEnumerable enumerables = number.Where(a => a > 50);
            foreach (var item in enumerables)
            {
                Console.Write(item+",");
            }
            //方法二
           IEnumerable result= MyWhere(number,
                delegate (int number) { return number > 50; }
                );
            foreach (var item in result)
            {
                Console.Write(item + ",");
            }
           
            //方法三
            IEnumerable result2 = MyWhere(number,a=>a>50);
            foreach (var item in result2)
            {
                Console.Write(item + ",");
            }

        }
       
        public static void Show() {
            Console.WriteLine("1111");
        }
        public static void Show2()
        {
            Console.WriteLine("2222");
        }
        public static bool isV(int number)
        {
            return number > 5;
        }
        public static IEnumerable MyWhere(int[] number, Func func) {

            foreach (var item in number)
            {
                if (func(item)==true)
                {
                    //进来一次返回出去一次
                    yield return item;
                }
            }
        }
    }
    delegate void F1();
    delegate bool F3(int number);

你可能感兴趣的:(.net,java,c#)