I have an interface method
public void Execute(ICommand command);
which needs to pass known subtypes of ICommand
to an apropriate Handle(SpecificCommand command)
method implementation and do some generic handling of unknown types. I am looking for a universal (i.e. not requiring a giant switch) method of doing so, something similar to
Handle(command as command.GetType()); // this obviously does not compile
I know I could register the handlers somehow, e.g. store them as delegates in a dictionary, but this still requires duplicating the handling logic (once in the specific Handle(...)
method signature, once in the delegate reqistration). If I populate the dictionary by inspecting my class with reflection (looking for Handle(XXX command)
methods), I'll get a performance hit.
To summarize: how can I downcast an object (upcasted by the call to Execute(ICommand command)
) to invoke a method requiring a concrete type without knowing which type it is at compile time.