본문 바로가기
개발/C#

Event와 Delegate의 차이

by 남생이야 2024. 6. 13.

 

Delegate 

 - Invoke 호출 범위에 대한 제약은 없다. 선언한 클래스 외에서도 해당 클래스를 참조하고 있다면 

델리게이트에 접근해서 호출할 수 있다. 

 - 외부에서 직접 호출이 가능하기 때문에 안정성이 떨어진다.

using System;

public class Program
{
    // 델리게이트 선언
    public delegate void Notify(string message);

    // 메서드
    public static void ShowMessage(string message)
    {
        Console.WriteLine(message);
    }

    public static void Main()
    {
        // 델리게이트 인스턴스 생성
        Notify notify = ShowMessage;

        // 델리게이트를 사용하여 메서드 호출
        notify("Hello, Delegates!");
    }
}

 

 

Event

- Delegate를 패킹(Packing)한 것이다. ( Delegate 기반)

- Invoke 호출은 해당 Event가 선언된 클래스 내에서만 사용할 수 있다. (캡슐화)

-  외부에서는 구독(+=)과 취소(-=)만 가능하다.

using System;

public class Program
{
    // 이벤트를 위한 델리게이트 선언
    public delegate void Notify(string message);

    // 이벤트 선언
    public event Notify OnNotify;

    // 이벤트를 발생시키는 메서드
    public void RaiseEvent(string message)
    {
        // 이벤트가 구독되었는지 확인하고 호출
        OnNotify?.Invoke(message);
    }

    public static void Main()
    {
        Program program = new Program();

        // 이벤트에 핸들러 등록
        program.OnNotify += ShowMessage;

        // 이벤트 발생
        program.RaiseEvent("Hello, Events!");

        // 이벤트 핸들러 메서드
        static void ShowMessage(string message)
        {
            Console.WriteLine(message);
        }
    }
}

 

'개발 > C#' 카테고리의 다른 글

[C#] 인터페이스(Interface)  (0) 2024.05.14
[C#]상속  (0) 2024.05.11
부분 클래스  (0) 2024.05.08
확장 메소드  (0) 2024.05.08
전처리기  (0) 2024.05.08