Monday, June 20, 2005
Reflection - Calling Methods using Reflection
To call a method of a type that is retrieved from System.Type, you will use the Invoke() method that is contained in MethodInfo.
ob is the reference to the object on which the method is invoked. For static method, ob should be null.
args specifies any arguments to be passed to the method. If no arguments, args should be null.
Args must contain exactly the same number of elements as there are arguments.
Here's a sub-program that does that:
(From C#: The Complete Reference by Schidlt)
object Invoke (object ob, object[] args)ob is the reference to the object on which the method is invoked. For static method, ob should be null.
args specifies any arguments to be passed to the method. If no arguments, args should be null.
Args must contain exactly the same number of elements as there are arguments.
Here's a sub-program that does that:
Type t = typeof(MyClass);
MyClass reflectOb = new MyClass(10, 20);
int val;
Console.WriteLine("Invoking methods in " + t.Name);
Console.WriteLine();
MethodInfo[] mi = t.GetMethods();
// Invoke each method
foreach (MethodInfo m in mi)
{
ParameterInfo[] pi = m.GetParameters();
if (m.Name == "set" && pi[0].ParameterType == typeof(int))
{
object[] args = new object[2];
args[0] = 9;
args[1] = 18;
m.Invoke(reflectOb, args);
}
}
(From C#: The Complete Reference by Schidlt)