Algo 쓰자

35. 델리게이트 체인(delegate chain) 본문

💻 Programming Language/C#

35. 델리게이트 체인(delegate chain)

S.Honey 2022. 4. 8. 09:13
  • 델리게이트 체인(delegate chain) : 델리게이트 하나가 여러개의 메소드를 동시에 참조하는 것.

사용 예제 코드


using System.Collections;

namespace DelegateEx
{
    delegate void CalDelegate(int x , int y);
    class Program 
    {
        static void Add(int x, int y)
        {
            Console.WriteLine(x + y);
        }

        static void Sub(int x, int y)
        {
            Console.WriteLine(x - y);
        }

        static void Mul(int x, int y)
        {
            Console.WriteLine(x * y);
        }

        static void Div(int x, int y)
        {
            Console.WriteLine(x / y);
        }


        static void Main(string[] args)
        {
            CalDelegate cd = Add; 
            // 첫번째 방법 `+=` 혹은 `-=`  사용
            cd += Sub;
            cd += Mul;
            cd += Div;

            cd(10, 5);

            Console.WriteLine("Multiply를 체이닝에서 제거");
            cd -= Mul;

            cd(10, 5);

            CalDelegate cd2 = new CalDelegate(Add) 
            // 두번째 방법 + new 연산자로 객체생성 및 `+` 연산사용.
                + Sub
                + Mul
                + Div;
            // 이렇게 체이닝을 해줘도 된다.

            cd(10, 5);

            CalDelegate cd3 = (CalDelegate)Delegate.Combine( 
                // 세번째 방법 Combine 함수 사용과 CalDelegate로 형변환 
                new CalDelegate(Add),
                new CalDelegate(Sub),
                new CalDelegate(Mul),
                new CalDelegate(Div)
                );

            cd(10, 5);
        }
    }
}
15
5
50
2
Multiply를 체이닝에서 제거
15
5
2
15
5
2
15
5
2
  • 총 세가지 방법을 이용해서 델리게이트 체인 을 구현했다.

  1. 첫번째 방법 += 혹은 -= 사용

             CalDelegate cd = Add; // 첫번째 방법 `+=` 혹은 `-=`  사용
             cd += Sub;
             cd += Mul;
             cd += Div;
    
             cd(10, 5);
    
             Console.WriteLine("Multiply를 체이닝에서 제거");
             cd -= Mul;
    
             cd(10, 5);

  1. 두번째 방법 new 연산자로 객체생성 및 + 연산사용.

             CalDelegate cd2 = new CalDelegate(Add) 
                 + Sub
                 + Mul
                 + Div;
    
             cd(10, 5);

  1. 세번째 방법 Combine 함수 사용과 CalDelegate로 형변환

             CalDelegate cd3 = (CalDelegate)Delegate.Combine( 
                 // 세번째 방법 Combine 함수 사용과 CalDelegate로 형변환 
                 new CalDelegate(Add),
                 new CalDelegate(Sub),
                 new CalDelegate(Mul),
                 new CalDelegate(Div)
                 );
    
             cd(10, 5);