In this post I'm showing the simplest usage of the system.reflection (forgive me for the case sensitivity, it's too problematic when there are a few editors open.)
The scenario is simple: a need to use a DLL, but not to use any real binding to it. In my work the need arose when we weren't sure which server has which version.
The simplest solution (from the programmer's point of view) is: "Use the latest version everywhere." Unfortunately, that's a "NO GO" due to the backwards compatibility tests needed.
The 2nd option is use reflection. How do you do that?
//This short code runs over the DLL's object-types, printing the basic details
System.Reflection.Assembly a = System.Reflection.Assembly.LoadFrom(args[0]);
foreach (Type tp in a.GetTypes())
{
Console.WriteLine(tp.FullName);
foreach (System.Reflection.MemberInfo inf in tp.GetMembers())
{
Console.WriteLine("(" + inf.MetadataToken.GetType().Name + ") " + inf.Name + " - " + inf.MemberType.ToString());
}
}
Usually we already know those details, but it's good to check the type of member you're gonna' access. There are some differences between accessing a variable and a property, methods certainly have a different approach and you know the rest...
How do I just use the bloody reflection?
1. Load the DLL:
System.Reflection.Assembly a = System.Reflection.Assembly.LoadFrom(args[0]);
2. Instantiate an object:
Type t = a.GetType(args[1]);
object o = Activator.CreateInstance(t);
NOTE: use the example program to find the Type if you encounter problems with the gettype.
3. Run a method:
object[] par = new object[] { false };
t.InvokeMember("A_Method", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, o, par);
Note:
You can use t.GetProperty("A_Property").GetValue(o, null); or t.GetField("A_Field").GetValue(o); to get properties' (fields') values. Set value has an additional field for the set value.
Sunday, April 13, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment