I have several classes designed to handle objects of certain types.
eg.
class FooHandler : Handler<Foo> { void ProcessMessage(Foo foo); }
where the handler interface can be defined something like this:
interface Handler<T> { void ProcessMessage(T obj); }
Now I would like to use the dictionary of these handlers:
Dictionary<Type, Handler> handlers; void ProcessMessage(object message) { var handler = handlers[message.GetType()]; handler.ProcessMessage(handler); }
However, C # prevents me from using the Handler interface without specifying a type. C # also does not allow declaring an interface Handler<out T> , so I cannot use Handler<object> in a handler declaration.
Even this does not work:
Dictionary<Type, object> handlers; void ProcessMessage(object message) { dynamic handler = handlers[message.GetType()]; handler.ProcessMessage(message); }
This seems solvable using reflection:
handler.GetType().GetMethod("ProcessMessage").Invoke(handler, new object[] { message });
And of course, I could remove the generics from the Handler interface. However, the reason I went this route is because I wanted to make the API for handlers as simple as possible. I wanted the classes to define the messages they receive, and that they could process these messages without having to enter parameters in each method.
I would rather avoid reflection, if possible, and generally avoid generics, not entirely satisfactory.
Am I missing something obvious or am I pushing the limits of C # generics?
I understand that C # is not Java (with Java type erasure, that would be easy), and maybe it could be better resolved in a more similar way to C # ... so I'm also interested in other approaches.
Thanks!