본문 바로가기
C#

[C#] 델리게이트(Delegate)와 이벤트(event)의 차이점

728x90
반응형

델리게이트(Delegate) 란?

delegate는 C#에서 제공해주는 메서드 참조자입니다. 일반 참조자와의 차이점은 '값'을 참조하는것이 아닌 하나의 함수를 참조한다는 것이 큰 차이점입니다. 기능자체는 C++의 함수포인터와 매우 유사하지만 C++에서는 제공해주지 않는 멀티캐스팅을 제공해줍니다.

 

멀티캐스팅(Multi Casting)이란?

멀티캐스팅은 여러개의 델리게이트들을 하나의 델리게이트로 묶어주는 기능입니다. 아래의 예제 코드처럼 델리게이트를 +, -연산자를 이용해 특정 델리게이트를 추가하고 제거할 수 있습니다. 언뜻 보면 없어도 되는 기능처럼 보일 수 있지만 특정 메소드 이후 꼭 실행되어야하는 메소드들을 묶어두는데 유용합니다.

using System;

// Define a custom delegate that has a string parameter and returns void.
delegate void CustomDel(string s);

class TestClass
{
    // Define two methods that have the same signature as CustomDel.
    static void Hello(string s)
    {
        Console.WriteLine($"  Hello, {s}!");
    }

    static void Goodbye(string s)
    {
        Console.WriteLine($"  Goodbye, {s}!");
    }

    static void Main()
    {
        // Declare instances of the custom delegate.
        CustomDel hiDel, byeDel, multiDel, multiMinusHiDel;

        // In this example, you can omit the custom delegate if you
        // want to and use Action<string> instead.
        //Action<string> hiDel, byeDel, multiDel, multiMinusHiDel;

        // Initialize the delegate object hiDel that references the
        // method Hello.
        hiDel = Hello;

        // Initialize the delegate object byeDel that references the
        // method Goodbye.
        byeDel = Goodbye;

        // The two delegates, hiDel and byeDel, are combined to
        // form multiDel.
        multiDel = hiDel + byeDel;

        // Remove hiDel from the multicast delegate, leaving byeDel,
        // which calls only the method Goodbye.
        multiMinusHiDel = multiDel - hiDel;

        Console.WriteLine("Invoking delegate hiDel:");
        hiDel("A");
        Console.WriteLine("Invoking delegate byeDel:");
        byeDel("B");
        Console.WriteLine("Invoking delegate multiDel:");
        multiDel("C");
        Console.WriteLine("Invoking delegate multiMinusHiDel:");
        multiMinusHiDel("D");
    }
}
/* Output:
Invoking delegate hiDel:
  Hello, A!
Invoking delegate byeDel:
  Goodbye, B!
Invoking delegate multiDel:
  Hello, C!
  Goodbye, C!
Invoking delegate multiMinusHiDel:
  Goodbye, D!
*/
// 출처 MS 공식문서 : https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/how-to-combine-delegates-multicast-delegates

이벤트(Event) 란?

특정 상황이나 조건에 실행되도록 만들어진 메소드입니다. 기존 delegate앞에 event문구를 추가해주는 것으로 구현이 가능합니다. 일반 delegate와 큰 차이가 없어보이지만 확실한 차이점이 존재합니다. 첫번째로 event는 Interface내에 선언이 가능합니다. 두번째로는 event는 접근제한에 상관없이 외부 클래스에서는 호출이 불가능하고 event호출을 통해서만 호출이 가능합니다. 이렇게 제한을 두는 이유는 delegate와 event의 사용목적이 다르기 때문입니다. delegate는 콜백 용도로 활용되고 event는 객체의 특정값 변화를 알리는용도로 사용됩니다.

반응형

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

[C#] 접근 한정자 internal의 사용법  (0) 2023.11.09
[C#] ref와 out, in의 차이점  (0) 2023.05.16
[C#] Boxing과 Unboxing  (1) 2023.02.18
[C#] 애트리뷰트(Attribute)  (0) 2023.02.13
[C#] 리플렉션 (Reflection)  (0) 2023.02.13