Using Reflections in .NET is – in particular – simple. You can always access meta data that is available in your execution assembly. And the more I get used to it, the more I use it for everyday problems. Last weekend for example I solved a problem that came up in a new framework I develop.
I wanted to decouple the dynamic creation of viewer instances for user interface model objects.
Imagine you create a button class (in pseudo-code):
class Button : Model { bool event Activated; Shape BackgroundShape; Shape ActivationShape; };
Soon you want to decouple the viewer logic from the button, so you create a separate class hierarchy with the abstract base class View:
class ButtonView : View { ButtonView(Button button); override void onMouseDown(); override void render(); }
An instance of this class is responsible for interfacing with the UI. It manages shape animation, mouse movement and raises – when the user clicks – the Button.Activated event.
Then, I imagined how I would like to create views without any knowledge about the Model.
Given a base class Model I wanted a method that creates the right View instance.
A naive attempt would be to declare a “createView()” method in the Model base class and override it in the derived ones. But this would imply that the model knows about its view, for which it really don’t cares.
Then an idea came up to use Reflection and tag the ButtonView’s constructor with an attribute. So the final code looked like:
class ButtonView : View { [MediatesTo(typeof(View))] ButtonView(Button button); override void onMouseDown(); override void render(); }
Using an extension method and a dictionary that maps the constructor’s first argument to the type that the MediatesTo attribute specifies, creating a view for any model finally resulted into:
Model button = new Button(); // 'button' could be any model for which a View exists. View view = button.mediateTo<View>(button);
This meta pattern is capable to decouple interfacing layers that needed to be created in frameworks. It may be used for View separation or platform bindings.
Anything You Can Do, I Can Do Meta – Charles Simonyi
yours
armin