委托作为参数传递

 class Program
    {
        static void Main(string[] args)
        {
            //将方法作为参数传递
            MyDelegate de = M1;
            Test(de);
            //执行test方法后重新调用
            de();
            Console.ReadKey();
        }
        //定义一个委托
        public delegate void MyDelegate();

        static void M1()
        {
            Console.WriteLine("方法一");
        }

        static void M2()
        {
            Console.WriteLine("方法二");
        }

        static void Test(MyDelegate d)
        {
            if (d != null)
            {
                d();
            }
            //改为与m2方法关联
            d = M2;
        }
    }

猜你喜欢

转载自www.cnblogs.com/jimtang/p/8978461.html