C#/수업내용

03/24 event연습

박준희 2021. 3. 24. 16:37
728x90

Program.cs

using System;

namespace Study07
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main");
            new App();
        }
    }
}

 

App.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace Study07
{
    public class App
    {
        //생성자 
        public App()
        {
            Console.WriteLine("App");

            DroneController controller = new DroneController();

            Drone drone1 = new Drone(100);
            Drone drone2 = new Drone(200);

            drone1.Init(controller);
            drone2.Init(controller);

            controller.Control(100, Drone.eDirection.UP);
            controller.Control(200, Drone.eDirection.UP);
            controller.Control(999, Drone.eDirection.BACK);
        }
        
    }

}

 

Drone.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study07
{
    public class Drone
    {
        public enum eDirection
        {
            FORWARD, BACK, LEFT, RIGHT, UP, DOWN
        }
        public int Id { get; private set; }
        private DroneController controller;
        public Drone(int id)
        {
            this.Id = id;
        }
        public void Init(DroneController controller)
        {
            this.controller = controller;
            this.controller.onMove += OnMoveEventHandler;
        }

        private void OnMoveEventHandler(object sender, DroneEventArgs e)
        {
            if(e.Id == this.Id || e.Id == 999)
            {
                this.Move(e.Dir);
            }
            else
            {
                Console.WriteLine("no signal..., id: {0}", this.Id);
            }
        }

        public void Move(eDirection dir)
        {
            Console.WriteLine("[MOVE] id: {0}, dir:{1}", this.Id, dir);
        }
        
    }
}

 

DroneController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study07
{
    public class DroneEventArgs : EventArgs
    {
        public Drone.eDirection Dir { get; private set; }
        public int Id { get; private set; }
        public DroneEventArgs(int id, Drone.eDirection dir)
        {
            this.Id = id;
            this.Dir = dir;
        }
    }
    public class DroneController
    {
        public event EventHandler<DroneEventArgs> onMove;
        public DroneController()
        {

        }
        public void Control(int id, Drone.eDirection dir)
        {
            DroneEventArgs args = new DroneEventArgs(id, dir);
            this.onMove(this, args);
        }
    }
}

 

728x90