Similarly to Kevin's answer, I'd consider taking advantage of the dynamic
keyword. I'll just mention two additional approaches.
Now, you don't really need access to the source code, you just need access to the types themselves, meaning, the assembly. As long as the types are public
(not private
or internal
) these should work:
Dynamic Visitor
This one uses a similar approach to the conventional Visitor pattern.
Create a visitor object, with one method for each sub-type (the end types, not intermediate or base classes such as Command
), receiving the external object as parameter.
Then to invoke it, on a specific object of which you don't know the exact type at compile-time, just execute the visitor like this:
visitor.Visit((dynamic)target);
You can also handle recursion within the visitor itself, for types that have sub-expressions you want to visit.
Dictionary of Handlers
Now, if you only want to handle a few of the types, not all of them, it may be simpler for you to just create a Dictionary
of handlers, indexed by Type
. That way you could check if the dictionary has a handler for the exact type, if it does, invoke it. Either through standard invocation which may force you to cast within your handler, or through a DLR invocation, which won't but will have a bit of a performance hit).