개발/C#

[C#] Delegate 사용 / 콜백 / 델리게이트

그린란드상어 2018. 12. 9. 11:59
반응형

2018/10/28 - [개발/C#] - 콜백함수 / Callback 함수 / C# Delegate


위 글에서 설명했던 Delegate를 사용해보자



//1. delegate 선언
delegate int delegateMath(int x, int y);

    class Program
    {
        public static int Plus(int x, int y)
        {
            return x + y;
        }

        public static int Minus(int x, int y)
        {
            return x - y;
        }

        static void Main(string[] args)
        {
            //2. delegate 생성
            delegateMath math = new delegateMath(Plus);
            //3. delegate 실행
            int res = math(5, 4);
            Console.WriteLine(" 5 + 4 = " + res);

            math = new delegateMath(Minus);
            Console.WriteLine(" 5 - 4 = " + math(5,4) );


        }
        
    }


1. delegate를 선언해준다


2. 선언한 delegate와 같은 매개변수와 반환타입을 가진 메서드 Plus, Minus를 정의한다.


3. 선언한 delegate 타입으로 delegate 변수를 생성하고, 해당 메서드 Plus, Minus를 참조시킨다.


3. delgate를 실행한다.






실제로는 이렇게 사용할 이유가 없지만, 사용법을 알기 위해 간단한 예제를 만들었다.


Delegate의 진정한 가치는 앞의 글에서 설명한 콜백메서드를 구현할 때 나타난다.


A라는 메서드를 호출할때 B메서드를 넘겨주어 A메서드가 원하는 시점에 B 메서드를 호출하도록 하는 것을 말하며


이때 A 메서드를 콜백메서드라한다.


위에서 작성한 예제에서는 delegate가 참조할 수 있는 메서드는 int뿐이었지만


delegate를 일반화 하면 어떤 타입의 메서드든지 참조 할 수 있다.



다음 예제를 보자


 delegate T delegateMath< t >(T x, T y);

    class Program
    {
        public static int Plus(int x, int y)
        {
            return x + y;
        }

        public static float Plus(float x, float y)
        {
            return x + y;
        }

        public static double Plus(double x, double y)
        {
            return x + y;
        }

        public static void Calc<T>(T a, T b, delegateMath<T> del)
        {
            Console.WriteLine(a + " + " + b + " = " + del(a, b));
        }

        static void Main(string[] args)
        {
            
            delegateMath<int>int_plus = new delegateMath<int>(Plus);
            delegateMath<float> float_plus = new delegateMath<float>(Plus);
            delegateMath<double> double_plus = new delegateMath<double>(Plus);

            Calc(3, 4, int_plus); //int 덧셈
            Calc(3.1f, 4.3f, float_plus); //float 덧셈
            Calc(3.2, 1.2, double_plus); //double 덧셈


        }
        
    }




다양한 타입의 plus 메서드를 참조할 수 있도록 Delegate를 일반화 하였다






마지막으로 Delegate Chain을 알아보자


지금까진 하나의 delegate에 하나의 메서드만 참조하였지만


delegate는 여러 메서드를 참조할 수 있다.


하나의 delegate에 여러 메서드를 연결시키는 것을 delegate Chain이라 한다.



    delegate void delegateMath(int x, int y);

    class Program
    {
        public static void Plus(int x, int y)
        {
            Console.WriteLine(x + " + " + y + " = " + (x + y) );
        }

        public static void Minus(int x, int y)
        {
            Console.WriteLine(x + " - " + y + " = " + (x - y));
        }

        static void Main(string[] args)
        {

            delegateMath math;
            math = new delegateMath(Plus);
            math += Minus;

            math(5, 4);

            math -= Minus;

            math(3, 2);

        }




위 예제처럼 += 을 이용하여 메서드를 추가하고, -= 을 이용하여 간단히 제거할 수 있다.


반응형