Reflector Class - Reflection Made Easy

snarfblam

Mega-Ultra Chicken
Joined
Jun 10, 2003
Messages
1,832
Location
USA
User Rank
*Expert*
Anyone who has spent more than a little bit of time getting their hands dirty with reflection will be well aware that all kinds of magic can happen through the System.Type.InvokeMember method. Unfortunately, though, this function has a large number of parameters to cover nearly every member invocation/access scenario and it can become tedious stringing together confusing parameter arrays and binding flags and determining which parameters are relevant for every invocation, and the resulting code is very difficult to read.

The Reflector class provides a number of methods that expose .Nets reflection capabilities in a more intuitive manner (and extends that functionality). Numerous overloads are provided for several clearly named functions that perform a specific type of reflection (method invocation, property getting, field setting, etc.). Additionally, the Reflector class uses a cut-down version of my Subscriber class to enable event handling through reflection.

Consider the following approximately equivalent code listings:
C#:
// Using standard reflection
Type myType = this.GetType();

// Change forms text
myType.InvokeMember("Text", 
    System.Reflection.BindingFlags.FlattenHierarchy | 
    System.Reflection.BindingFlags.Instance | 
    System.Reflection.BindingFlags.Public | 
    System.Reflection.BindingFlags.SetProperty, 
    null, this, new object[] { "Reflected!" });

// Change forms private dialogResult field
myType.InvokeMember("dialogResult",
    System.Reflection.BindingFlags.FlattenHierarchy |
    System.Reflection.BindingFlags.Instance |
    System.Reflection.BindingFlags.NonPublic |
    System.Reflection.BindingFlags.SetField,
    null, this, new object[] { DialogResult.OK });

// Hide the form
myType.InvokeMember("Hide",
    System.Reflection.BindingFlags.FlattenHierarchy |
    System.Reflection.BindingFlags.Instance |
    System.Reflection.BindingFlags.Public |
    System.Reflection.BindingFlags.InvokeMethod,
    null, this, new object[0]);

C#:
// Using Reflector
Reflector Me = new Reflector(this);

// Change forms text
Me.SetProperty("Text", "Reflected!");
 
// Change forms private dialogResult field
Me.PrivateAccess = true;
Me.SetField("dialogResult", DialogResult.OK);
 
// Hide the form
Me.InvokeMethod("Hide", Me.NoArgs);
Not all overloads of all methods have been tested thouroughly. Feel free to post questions, comments and bugs.
 

Attachments

Updated Reflector class to climb inheritance hierarchy to find private members of base classes.
 

Attachments

Fixed a big in Reflector.cs and then converted the class to VB. Note that I did very little testing on the VB version and it is very possible that a bug or two or ten were introduced in the translation.
 

Attachments

Back
Top