공부/c#

c# delegate, event

Lectinua 2019. 6. 7. 04:46

delegate 예제)

 

namespace DelegatePrac2
{
    delegate void DelegateType();

    class A
    {
        public void PrintA()
        {
            Console.WriteLine("PrintA");
        }

        public void PrintB()
        {
            Console.WriteLine("PrintB");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            A Test = new A();
            DelegateType DelFunc = Test.PrintA;
            DelFunc += Test.PrintB;
            DelFunc();
            DelFunc -= Test.PrintB;
            DelFunc();
        }
    }
}

 

event 예제)

 

namespace EventPrac
{
    delegate void DelegateType(string Message);

    class A
    {
        public event DelegateType EventHandler;
        public void Func(string Message)
        {
            EventHandler(Message);
        }
    }

    class B
    {
        public void PrintA(string Message)
        {
            Console.WriteLine("A: " + Message);
        }
        public void PrintB(string Message)
        {
            Console.WriteLine("B: " + Message);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            A Test1 = new A();
            B Test2 = new B();

            Test1.EventHandler += new DelegateType(Test2.PrintA);
            Test1.EventHandler += new DelegateType(Test2.PrintB);
            Test1.Func("Good!!!");
            Test1.EventHandler -= Test2.PrintB;
            Test1.Func("Hi~~!");
            Test1.EventHandler -= Test2.PrintA;

            Test1.EventHandler += Test2.PrintA; //처리기에 추가하기
            Test1.EventHandler += Test2.PrintB;
            Test1.Func("Hello World");
        }
    }
}

 

출력 결과

A: Good!!!

B: Good!!!

A: Hi~~!

A: Hello World

B: Hello World

 

출처: https://www.youtube.com/watch?v=B-yaWp900sQ&t=1750s