C# 如何将方法作为参数传递

如何实现将方法作为参数传递

示例是控制台程序,代码如下:

    class Program
    {
        static void Main(string[] args)
        {
            FuncB(FuncA,x);
            Console.WriteLine("c:"+c.ToString());
            Console.ReadKey();
        }

        static int a = 2;
        static int b = 3;
        static int c = 0;
        static int x = 4;

        //声明一个方法型,关键字就是delegate,有参数就带上参数
        public delegate void FuncA_EventHandler(int aa);
        //用上面的方法类型声明一个对象_funcA
        static FuncA_EventHandler _funcA;

        //需要作为参数传递的方法FuncA
        public static void FuncA(int x)
        {
            c = (a + b) * x;
        }
        //以FuncA为参数的方法FuncB,FuncA有参数,FuncB也加一个就行了
        public static void FuncB(FuncA_EventHandler funcA,int x)
        {
            _funcA = funcA;
            if (_funcA!=null)
            {
                _funcA(x);
            }
            //_funcA?.Invoke(2);//简化写法
        }
    }

运行结果:

 

posted @ 2020-12-03 11:27  沛苍冥  阅读(6297)  评论(0编辑  收藏  举报