본문 바로가기

C# 문법

[C#] EventHandler - 이벤트에 특정값(Class)전달

EvenHandler

  • 일반적인 EventHander는 이벤트 발생시 전달할 값이 없는 이벤트를 나타냅니다.
  • public delegate void EventHandler(object? sender, EventArgs arg);

매개 변수

  • Sender => Object 이벤트 호출자, 이벤트 소스라 불립니다.
  • arg => EventArgs 이벤트 데이터가 포함되지 않은 개체입니다.
  • 그냥 이벤트 호출자의 정보(sender)를 전달하거나, 혹은 이벤트를 통해 해당시 점의 특정 메서드를 실행시킬 때 사용>

EvntHander 사용 방법

    //이벤트를 선언
    private event EventHandler ShowMessage;
    public void Run()
    {
        //단지 Event를 통해 ShowMessage를 보여주고 싶었습니다.
        ShowMessage += new EventHandler(ShowMessage_Event);
        if (ShowMessage != null)
            ShowMessage(this, null);
    }

    private void ShowMessage_Event(object sender, EventArgs e)
    {
        Console.WriteLine("봄날은 온다~!");
    }

결과

봄날은 온다~!

그렇다면, 특정 값을 전달하고 싶다면?

public delegate void EventHandler(object? sender, TEventArgs e);

  • TEventArgs는 이벤트시 전달할 매개변수 입니다.

EvntHander 사용 방법

    //이벤트를 선언
    private event EventHandler<PersonalInformation> ShowMessage;
    public void Run()
    {
        //이벤트가 발생했을대 어떤 행동을 할 것인지 지정해준다.
        ShowMessage += new EventHandler<PersonalInformation>(ShowMessage_Event);
        //만약 OccurrenceEvent가 선언되어 있다면 이벤트 발생!
        if (ShowMessage != null)
        {
            PersonalInformation pInfo = new PersonalInformation();
            pInfo.Name = "양뱅";
            pInfo.Age = 33;
            ShowMessage(null, pInfo); //이렇게 Class을 전달 할때도 사용!!
        }
    }
    private class PersonalInformation
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    private void ShowMessage_Event(object sender, PersonalInformation e)
    {
        Console.WriteLine($"{e.Name} , {e.Age}");
    }

결과

양뱅 , 33