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);//简化写法
        }
    }

运行结果:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM