I'm trying to have a List
of open generic types. Is it possible to have something like:
public class MessageProcessor
{
private IDictionary<Type, IMessageHandler<>> _messageHandlers
= new Dictionary<Type, IMessageHandler<>>();
public void AddHandler<TMessage>(IMessageHandler<TMessage> handler)
{
var messageType = typeof(TMessage);
// Add to dictionary here
}
public void Handle<TMessage>(TMessage message)
{
// Call the correct handler here.
}
}
IMessageHandler
should have a strongly typed method:
public void Handle(TMessage message) {}
My real example is a little more complex, so I hope I've simplified it correctly here.
The fact is, I'm not interested in what the generic type is of each handler. I just need all of them in one place, and I can easily find the correct handler, if I can get them in that one place.
The private Dictionary will have the Type of the message (TMessage) as key. So I want to be able to do:
// ByteArrayHandler implements IMessageHandler<byte[]>
x.AddHandler(new ByteArrayHandler())
// StringHandler implements IMessageHandler<string>
x.AddHandler(new StringHandler())
x.Handle("Some message");
x.Handle(new byte[] { 1, 2, 3} );
And have the MessageProcessor
call the correct MessageHandler
.
IDictionary<Type, object>
sounds like it would work? – PolyhydricIMessageHandler
expose aType
property that tells you what it handles rather than making it generic? – ArgyresHandle
method is generic, but it doesn't really gain you anything because they're only used at runtime. – Schnell