C# 复习(1) 委托与事件

委托定义顺序

1. 声明一个委托

2.定义一个委托变量

3. 委托变量的初始化或者给委托变量绑定一个方法

4.调用委托

事件:事件是对委托的封装。

事件只能在创建事件的类的内部调用。

    public class Controller
    {

        public delegate void stopMachineryDelegate();
        public event stopMachineryDelegate StopMachine;
        public void ShutDown()
        {
            for (int i = 0; i < 100; i++)
            {
                if (i > 50)
                {
                    if (this.StopMachine != null)
                    {
                        this.StopMachine();
                    }
                }
            }
            
        }
    }
   static void Main(string[] args)
        {
            Controller controller=new Controller();

            FoldingMachine folder = new FoldingMachine();
            PaintingMachine painter = new PaintingMachine();
            WeldingMachine welder = new WeldingMachine();

            controller.StopMachine += folder.StopFolding;
            controller.StopMachine += painter.PaintOff;
            controller.StopMachine += welder.FinishWelding;

            controller.ShutDown();

            Console.ReadKey();

        }

 

 

你可能感兴趣的:(C#)