委托学习小案例三——Action<>

委托学习小案例三——Action<>

class Program
    {
        static void Main(string[] args)
        {
            //无参数无返回值的委托
            Action action1 = new Action(ActionWithNoParaNoReturn);
            action1();
            Console.WriteLine("----------------------------");
            // 使用delegate
            Action action2 = delegate { Console.WriteLine("这里是使用delegate"); };
            // 执行
            action2();
            Console.WriteLine("----------------------------");
          
            // 使用匿名委托
            Action action3 = () => { Console.WriteLine("这里是匿名委托"); };
            action3();
            Console.WriteLine("----------------------------");
            
            // 有参数无返回值的委托
            Action<int> action4 = new Action<int>(ActionWithPara);
            action4(23);
            Console.WriteLine("----------------------------");
          
            // 使用delegate
            Action<int> action5 = delegate (int i) { Console.WriteLine($"这里是使用delegate的委托,参数值是:{i}"); };
            action5(45);
            Console.WriteLine("----------------------------");
            
            // 使用匿名委托
            Action<string> action6 = (string s) => { Console.WriteLine($"这里是使用匿名委托,参数值是:{s}"); };
            action6("345");
            Console.WriteLine("----------------------------");
            
            // 多个参数无返回值的委托
            Action<int, string> action7 = new Action<int, string>(ActionWithMulitPara);
            action7(7, "abc");
            Console.WriteLine("----------------------------");
           
            // 使用delegate,Action就是无返回值的委托
            Action<int, int, string> action8 = delegate (int i1, int i2, string s)
            {
                Console.WriteLine($"这里是三个参数的Action委托,参数1的值是:{i1},参数2的值是:{i2},参数3的值是:{s}");
            };
            action8(12, 34, "abc");
            Console.WriteLine("----------------------------");
            Action<int, int, string, string> action9 = (int i1, int i2, string s1, string s2) =>
            {
                Console.WriteLine($"这里是使用四个参数的委托,参数1的值是:{i1},参数2的值是:{i2},参数3的值是:{s1},参数4的值是:{s2}");
            };
            // 执行委托
            action9(34, 56, "abc", "def");
            Console.ReadKey();
        }

        #region Method
        //定义无参数的引用方法
        static void ActionWithNoParaNoReturn()
        {
            Console.WriteLine("这是无参数无返回值的Action委托");
        }

        //定义单个参数的引用方法
        static void ActionWithPara(int i)
        {
            Console.WriteLine($"这里是有参数无返回值的委托,参数值是:{i}");
        }

        //定义2个参数的引用方法
        static void ActionWithMulitPara(int i, string s)
        {
            Console.WriteLine($"这里是有两个参数无返回值的委托,参数1的值是:{i},参数2的值是:{s}");
        }
        #endregion
    }

 

posted @ 2021-05-14 16:33  码农阿亮  阅读(85)  评论(0编辑  收藏  举报