Runtime reflection provides the ability to dynamically invoke methods. The nonstatic methods require a parameter indicating the instance to invoke the method on. The following C# code fragment demonstrates this method.
using System; using System.Reflection; public class MyRandom { public static void Main(string[] args) { Type type = Type.GetType("System.Random"); // Create an instance of the Random class using the default // constructor. Object obj = Activator.CreateInstance(type); try { // Create an array of Type objects that represent // the parameter list for list for the Random.Next method // that takes an int as a parameter. Type[] paramTypes = new Type[1]; paramTypes[0] = Type.GetType("System.Int32"); // Get the Random::Next method that takes an int as a // parameter. // This method generates a random number between 0 and the // value of the argument passed in. MethodInfo method = type.GetMethod("Next", paramTypes); // Call the Random::Next method with an initial value of 100, // and then repeatedly call the method with the result of the // previous invocation. This will result in a decreasing // sequence of numbers, which will be written to the console. int i = 0; Object randomNumber; Object[] randomArgs = new Object[1]; // argument list randomArgs[0] = 100; do { // Invoke this method with the given values randomNumber = method.Invoke(obj, randomArgs); // Print the return value Console.Write("Random Number ("); Console.Write(i++); Console.Write("): "); Console.WriteLine(randomNumber.ToString()); randomArgs[0] = randomNumber; } while (Convert.ToInt32(randomNumber) > 0); } catch (TargetInvocationException e) { Console.Write("Target throw this exception: "); Console.WriteLine(e.InnerException); } } // end main }
Of course, you can invoke methods that take arguments as well. However, the arguments supplied must match exactly the arguments to the method being called. No automatic narrowing conversions are performed. Only widening conversions are done automatically. These include class to base class conversions and standard widening conversions of intrinsic types that are detailed below:
Please see the Base Data Type Specification for a list of the standard conversions we do in reflection.