I have a Dictionary to map a certain type to a certain generic object for that type. For example:
typeof(LoginMessage) maps to MessageProcessor
You can write a method that takes the type as a generic parameter:
void GenericProcessMessage(T message)
{
MessageProcessor processor = messageProcessors[typeof(T)]
as MessageProcessor;
// Call method processor or whatever you need to do
}
Then you need a way to call the method with the correct generic argument. You can do this with reflection:
public void ProcessMessage(object message)
{
Type messageType = message.GetType();
MethodInfo method = this.GetType().GetMethod("GenericProcessMessage");
MethodInfo closedMethod = method.MakeGenericMethod(messageType);
closedMethod.Invoke(this, new object[] {message});
}