본문 바로가기
C#/C# Common

Event

by doublerabbits 2022. 8. 30.

Event

 

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

namespace Event
{
    class Program
    {
        static void Main(string[] args)
        {
            var tower = new ClockTower();
            var john = new Person("John", tower);

            tower.ChimeFivePM();
            tower.ChimeSixAM();

            Console.ReadKey();
        }
    }

    public class Person
    {
        private string _name;
        private ClockTower _tower;
        public Person(string name, ClockTower tower)
        {
            _name = name;
            _tower = tower;

            _tower.Chime += (object sender, ClockTowerEvnetArgs args) => { 
                Console.WriteLine("{0} heard the clock chime.", _name); 
                switch(args.Time)
                {
                    case 6:
                        Console.WriteLine("{0} is waking up.", _name);
                        break;

                    case 17:
                        Console.WriteLine("{0} is going home.", _name);
                        break;
                }
            };
        }        
    }

    public class ClockTowerEvnetArgs : EventArgs
    {
        public int Time { get; set; }
    }

    public delegate void ChimeEventHandler(object sender, ClockTowerEvnetArgs args);
    public class ClockTower
    {
        public event ChimeEventHandler Chime;

        public void ChimeFivePM()
        {
            Chime(this, new ClockTowerEvnetArgs { Time = 17 });
        }
        
        public void ChimeSixAM()
        {
            Chime(this, new ClockTowerEvnetArgs { Time = 6 });
        }
    }
}

 

 

 

 

 

 

Anonymous Methods and Lambda Expression

 

Anonymous Methods and Lambda Expression

아래 기술된 코드는 실행 결과가 모두 같다. 익명 함수에서 람다식으로 변형되는 과정이다. 방식 1 using System; namespace AnonymousMethodAndLambda { internal class Program { delegate void Operation(int n..

doublerabbits.tistory.com

 

 

 

https://www.youtube.com/watch?v=KVp_E-hTG0k 

 

'C# > C# Common' 카테고리의 다른 글

Extension Methods  (0) 2022.09.03
LINQ  (0) 2022.09.01
Anonymous Methods and Lambda Expression  (0) 2022.08.30
Generic  (0) 2022.08.16
가변 인수  (0) 2022.06.30