C# 문법 공부 : DelegateSample

 

using System;

namespace DelegateSample;

class Program
{
    static void Main(string[] args)
    {
       new DelegateEventP().test();
       //new DelegateEventI().test();
    }
}

 

 

 

Delegate1

using System;
using DelegateSample;

namespace DelegateSample;

    class Delegate1
    {
        
        static void Main(string[] args)
        {
            Delegate1 d1 = new Delegate1();
            d1.Perform();
        }

        private delegate void RunDelegate(int i);// 1. delegate 선언

        private void RunThis(int val)
        {
            Console.WriteLine("1.{0}", val);    // 콘솔출력 : 1024
        }

        private void RunThat(int value)
        {
            Console.WriteLine("2.{0}", value);  // 콘솔출력 : 0x400
        }

        public void Perform()
        {
            RunDelegate run = new RunDelegate(RunThis); // 2. delegate 인스턴스 생성
            run(1024);                                  // 3. delegate 실행
            
            run = RunThat; //run = new RunDelegate(RunThat); 을 줄여서 쓸 수있다.
            run(1024);
        }
    }

 

 

 

 

Delegate2

using System;
using DelegateSample;

namespace DelegateSample;
    class Delegate2
    {
        static void Main(string[] args)
        {
            new Program().Test();
        }
        
        // 델리게이트
        delegate int MyDelegate(string s);
        
        void Test()
        {
            // 델리게이트 객체 생성
            MyDelegate m = new MyDelegate(StringToInt);
            
            // 델리게이트 객체를 메서드로 전달
            Run(m);
        }
        
        // 델리게이트 대상이 되는 어떤 메서드
        int StringToInt(string s)
        {
            return int.Parse(s);
        }
        
        // 델리게이트를 전달 받는 메서드
        void Run(MyDelegate m)
        {
            // 델리게이트로부터 메서드 실행
            int i = m ("123");
            
            Console.WriteLine(i); // 결과값 123
        }
        
    }

 

 

 


Delegate3

using System;
using DelegateSample;

namespace DelegateSample;

    delegate int PDelegate(int a, int b);

    class Delegate3
    {
        static int Plus(int a, int b)
        {
            return a + b;
        }

        public void Test()
        {
            PDelegate pd1 = Plus;
            PDelegate pd2 = delegate(int a, int b)
            {
                return a / b;
            };
            Console.WriteLine( pd1(5,10));  // a+b=15
            Console.WriteLine( pd2(10,5));  // a/b=2
        }
    }

 

 

 


DelegateCombine

 

using System;
using DelegateSample;

namespace DelegateSample;

    delegate void PDelegate2(int a, int b);

    class PDelegateCombine
    {
        static void Plus(int a, int b)
        {
            Console.WriteLine("{0} + {1} = {2}", a, b, a+b );
        }

        static void Minus(int a, int b)
        {
            Console.WriteLine("{0} - {1} = {2}", a, b, a-b );
        }

        public void Test()
        {
            //Delegate.Combine(여러개 동시에 호출)
            PDelegate2 pd = (PDelegate2)Delegate.Combine(new PDelegate2(Plus),new PDelegate2(Minus));
            pd(20,10);
        }
    }

 

 


 

 

DelegateEventI

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

namespace DelegateSample;

    //델리게이트 MyEventHandler 선언
    //접근한정자 + delegage + 반환형 + delegate이름();
    public delegate void OnInputKey();

    class InputManager
    {
        //이벤트 MyEventHandler 등록
        //접근한정자 + event +  delegate이름 + 이벤트이름;
        public event OnInputKey InputKey;

        public void Update()
        {                                               //Console.KeyAvailable 입력 스트림에서 키 누름을 사용할 수 있는지를 나타내는 값을 가져옴
            if(Console.KeyAvailable == false) return;   //2. 키 누름을 사용할 수 있으면 true 사용 못하면 false
                                                      
            ConsoleKeyInfo info = Console.ReadKey();    //3. Console.ReadKey() 다음 문자나 사용자가 누른 기능 키를 가져옴

            if(info.Key == ConsoleKey.A) InputKey();    //4. A키가 눌리면 델리게이트 OnInputKey(OnInptuTest) 실행
        }
    }

    class DelegateEventI
    {
        //델리게이트를 이용하여 넘겨줄 메소드
        static public void OnInputTest()
        {
            Console.WriteLine("");                      //5.메시지 출력
            Console.WriteLine("Input Received!");
        }

        public void test()
        {
            InputManager inputManager = new InputManager();         //InputManager 클래스 초기화
            inputManager.InputKey += new OnInputKey(OnInputTest);   //inputManager 클래스 InputKey 이벤트에 델리게이트 OnInputKey(OnInptuTest) 등록
                                                                    //InputKey 이벤트 발생시 OnInputKey(OnInptuTest) 호출
            while(true)
            {
                inputManager.Update();  //1. Update 함수 호출
            }                           //InputManager 클래스의 외부라서 'inputManager.InputKey()' 이벤트 직접 호출 불가능
        }
}

 


DelegateEventP

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

namespace DelegateSample;

    //델리게이트 MyEventHandler 선언
    //접근한정자 + delegage + 반환형 + delegate이름();
    public delegate void MyEventHandler(string message);

    class Publisher
    {
        //이벤트 MyEventHandler 등록
        //접근한정자 + event +  delegate이름 + 이벤트이름;
        public event MyEventHandler Active;

        public void DoActive(int number)
        {
            if( number%10 == 0){            //2-1.number가 나머지가 0이면 
                Active("Active! " + number);//2-2.델리게이트 MyEventHandler(MyHandler) 이벤트 발생
            }else{                          //3-1. number 나머지가 0이 아니면
                Console.WriteLine(number);  //3-2. number 출력 후 종료
            }
        }
    }

    class DelegateEventP //subscriber(구독자)
    {
        //델리게이트를 이용하여 넘겨줄 메소드
        static public void MyHandler(string message)//2-3.Active()가 호출 될때 발생
        {
            Console.WriteLine(message);             //2-4. message 콘솔 출력 후 종료
        }

        public void test()
        {
            Publisher publisher = new Publisher();              //Publisher 클래스 선언
            publisher.Active += new MyEventHandler(MyHandler);  //Publisher클래스 Active 이벤트에 MyEventHandler(MyHandler) 델리게이트 등록
                                                                //Active 이벤트 발생시 MyEventHandler(MyHandler) 호출
            for (int i=0; i<50; i++)
            {
                publisher.DoActive(i);  //1.DoActive()함수 호출
            }
        }
}

 

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

C# 문법 공부 : Generics  (1) 2024.04.29
C# 문법 공부 : Files  (0) 2024.04.29
C# 문법 공부 : Network  (0) 2024.04.29
C# 문법 공부 : class 6~9  (0) 2024.04.29
C# 문법 공부 : class 2~5  (0) 2024.04.29