Hi,
I'm currently writing an event-based messaging system and have encountered a problem. Basically I want to be able to do this:
I've reduced the problem so it looks like this:
The problem is in the Register method where the compiler complains that I cannot convert type System.Action<T> to System.Action<IEvent>. Does anybody know a way around this? I.E without changing the Register-method interface.
Thanks
I'm currently writing an event-based messaging system and have encountered a problem. Basically I want to be able to do this:
C#:
// Use a lambda
EventManager.Register<TestEvent1>((@event) =>
{
//Do something with event
});
// or use a method
EventManager.Register<TestEvent2>(OnTestEvent);
private void OnTestEvent(TestEvent2 @event)
{
//Do something with event
}
I've reduced the problem so it looks like this:
C#:
public interface IEvent { }
public class TestEvent1 : IEvent {}
public class TestEvent2 : IEvent {}
public class EventManager
{
private Dictionary<Type, Action<IEvent>> actions = new Dictionary<Type, Action<IEvent>>();
public void Register<T>(Action<T> @event) where T : IEvent
{
actions[typeof(T)] = @event;
}
public void Push(IEvent @event)
{
actions[@event.GetType()](@event);
}
}
The problem is in the Register method where the compiler complains that I cannot convert type System.Action<T> to System.Action<IEvent>. Does anybody know a way around this? I.E without changing the Register-method interface.
Thanks
Last edited: