A lightweight .NET reflection library featuring utilities for hierarchy traversal and a powerful universal event handler.
$ dotnet add package OutWit.Common.ReflectionThe EventUtils class provides utilities for working with .NET events, enabling developers to create universal handlers for any event in a highly reusable and reflective manner. This is particularly useful in scenarios requiring dynamic event handling or generalized solutions for complex event-driven architectures.
The GetAllEvents method recursively retrieves all events from a given type, including:
Type type = typeof(SomeClass);
IEnumerable<EventInfo> allEvents = type.GetAllEvents();
foreach (var eventInfo in allEvents)
{
Console.WriteLine(eventInfo.Name);
}
The CreateUniversalHandler method allows you to create a delegate for any event using a universal handler. This handler acts as a single entry point for all events of a type, dynamically handling event calls.
using OutWit.Common.Reflection;
public class Example
{
public static void Main()
{
var obj = new SomeClass();
EventInfo eventInfo = typeof(SomeClass).GetEvent("SomeEvent")!;
var handler = eventInfo.CreateUniversalHandler(
obj,
(sender, eventName, parameters) =>
{
Console.WriteLine($"Event {eventName} triggered on {sender} with parameters: {string.Join(", ", parameters)}");
});
eventInfo.AddEventHandler(obj, handler);
obj.TriggerSomeEvent(); // Triggers the universal handler
}
}
public class SomeClass
{
public event EventHandler? SomeEvent;
public void TriggerSomeEvent()
{
SomeEvent?.Invoke(this, EventArgs.Empty);
}
}
GetAllEventspublic static IEnumerable<EventInfo> GetAllEvents(this Type type)
EventInfo objects.CreateUniversalHandlerpublic static Delegate CreateUniversalHandler<TSender>(
this EventInfo me,
TSender sender,
UniversalEventHandler<TSender> handler
) where TSender : class;
me: The EventInfo describing the event.sender: The object raising the event.handler: The universal event handler delegate.Delegate matching the event's signature.UniversalEventHandlerA delegate used for the universal handler:
public delegate void UniversalEventHandler<in TSender>(
TSender sender,
string eventName,
object[] parameters
) where TSender : class;
sender: The object that raised the event.eventName: The name of the event.parameters: The event arguments passed during invocation.Include the OutWit.Common.Reflection namespace in your project to access EventUtils.
Licensed under the Apache License, Version 2.0. See LICENSE.
If you use OutWit.Common.Reflection in a product, a mention is appreciated (but not required), for example: "Powered by OutWit.Common.Reflection (https://ratner.io/)".
"OutWit" and the OutWit logo are used to identify the official project by Dmitry Ratner.
You may:
You may not: