2016년 8월 23일 화요일

[C#강좌,닷넷강좌,IT실무교육★탑크리에듀][C#예제]델리게이트 체인/멀티캐스팅예제,닷넷Delegate,Delegate.Combine

[C#예제]델리게이트 체인/멀티캐스팅예제,닷넷Delegate,Delegate.Combine

델리게이트 체인은 하나의 델리게이트에 여러 델리게이트를 체인처럼 연결해서 한번에 실행할 수 있는 방법을 제공한다.

Delegate.Combine으로 여러 델리게이트를 연결하는데 이는 델리게이트 멀티캐스팅 형태로 변환 가능하다. 아래 예제를 참조하자.

using System;
namespace ConsoleApplication6
{
    delegate void OnjDelegate(int a, int b);
    class MainApp
    {
        static void Plus(int a, int b) { Console.WriteLine("{0} + {1} = {2}", a, b, b); }
        static void Minus(int a, int b) { Console.WriteLine("{0} - {1} = {2}", a, b, a - b); }
        void Multiplication(int a, int b) { Console.WriteLine("{0} * {1} = {2}", a, b, a * b); }
        void Division(int a, int b) { Console.WriteLine("{0} / {1} = {2}", a, b, a / b); }
        static void Main()
        {
            MainApp m = new MainApp();
            OnjDelegate CallBack = (OnjDelegate)Delegate.Combine(
            new OnjDelegate(MainApp.Plus),
            new OnjDelegate(MainApp.Minus),
            new OnjDelegate(m.Multiplication),
            new OnjDelegate(m.Division));
            CallBack(4, 3);
            Console.WriteLine("-----------------");

            OnjDelegate CallBack2 = new OnjDelegate(MainApp.Plus);
            CallBack2 += new OnjDelegate(MainApp.Minus);
            CallBack2 += new OnjDelegate(m.Multiplication);
            CallBack2 += new OnjDelegate(m.Division);
            CallBack2(4, 3);
            Console.WriteLine("-----------------");

            OnjDelegate CallBack3_1 = new OnjDelegate(MainApp.Plus);
            OnjDelegate CallBack3_2 = new OnjDelegate(MainApp.Minus);
            OnjDelegate CallBack3_3 = new OnjDelegate(m.Multiplication);
            OnjDelegate CallBack3_4 = new OnjDelegate(m.Division);
            OnjDelegate CallBack3 = CallBack3_1 + CallBack3_2 + CallBack3_3 + CallBack3_4;
            CallBack3(4, 3);
        }

    }
}


[결과]
4 + 3 = 3
4 - 3 = 1
4 * 3 = 12
4 / 3 = 1
-----------------
4 + 3 = 3
4 - 3 = 1
4 * 3 = 12
4 / 3 = 1
-----------------
4 + 3 = 3
4 - 3 = 1
4 * 3 = 12
4 / 3 = 1

댓글 없음:

댓글 쓰기