C# .NET Framework에서 발생하는 시스템 이벤트와 별도로 사용자가 직접 이벤트를 정의하여 사용할 수 있다. 이벤트를 받을 때 파라미터로 데이터를 받으려면 EventArgs 클래스를 상속받아 여기에 항목을 추가하여 사용이 가능하다. WinForm이나 WPF에서 제공하는 이벤트와 별도로 개발자가 직접 이벤트 로직을 만들 수 있어야 한다. 전체 소스는 UserEventExam 에서 볼 수 있다.
UserEvents.cs
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
using System;
namespace UserEventExam
{
public class UserArgs : EventArgs
{
public string Name { get; set; }
public int Age { get; set; }
}
}
Database.cs
using System;
namespace UserEventExam
{
public class Database
{
public void SendData(object sender, UserArgs e)
{
Console.WriteLine($"Data : User({e.Name}), Age({e.Age}), object({sender})");
}
}
}
Program.cs
namespace UserEventExam
{
internal class Program
{
private static void Main()
{
var db = new Database();
UserEvents.OnUserEvent += db.SendData;
const string name = "홍길동";
const int age = 30;
UserEvents.ProcessEvent(new UserArgs() {Name = name, Age = age});
}
}
}