
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Dynamically Invoking Members
|
779
These are the dynamically invoked methods located on the SampleClass type in the
SampleClassLibrary assembly:
public bool TestMethod1(string text)
{
Console.WriteLine(text);
return (true);
}
public bool TestMethod2(string text, int n)
{
Console.WriteLine(text + " invoked with {0}",n);
return (true);
}
The output from these methods looks like this:
Running TestMethod1
Returned object: True
Returned object: System.Boolean
Running TestMethod2 invoked with 27
Returned object: True
Returned object: System.Boolean
Discussion
Reflection gives you the ability to dynamically invoke both static and instance meth-
ods within a type in either the same assembly or in a different one. This can be a very
powerful tool to allow your code to determine at runtime which method to call. This
// For each parameter, add it to the list.
foreach (object parameter in parameters)
{
// Get the type of the parameter.
Type paramType =
invokedMethod.GetParameters( )[index].ParameterType;
// Change the value to that type and assign it.
parameters[index] =
Convert.ChangeType(parameter, paramType);
index++;
}
// Invoke the method with the parameters.
object retObj = invokedMethod.Invoke(dynObj, parameters);
// Return the returned object.
return (retObj);
}
}
return (null);
}
Example 13-5. ...