DevSight

C#에서 사용자 정의 Event 만들기

C# .NET Framework에서 발생하는 시스템 이벤트와 별도로 사용자가 직접 이벤트를 정의하여 사용할 수 있다. 이벤트를 받을 때 파라미터로 데이터를 받으려면 EventArgs 클래스를 상속받아 여기에 항목을 추가하여 사용이 가능하다.

WinForm이나 WPF에서 제공하는 이벤트와 별도로 개발자가 직접 이벤트 로직을 만들 수 있어야 한다. 전체 소스는 UserEventExam 에서 볼 수 있다.

UserEvents.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;

namespace UserEventExam
{
    public class UserEvents
    {
        public static event EventHandler<UserArgs> OnUserEvent;

        public static void ProcessEvent(UserArgs args)
        {
            OnUserEvent?.Invoke(OnUserEvent.Target, args);
        }
    }
}
UserArgs.cs
1
2
3
4
5
6
7
8
9
10
using System;

namespace UserEventExam
{
    public class UserArgs : EventArgs
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}
Read More ···