Reflection: How to call Methods dynamically at runtime
using System;
using System.Reflection;
using System.Collections.Generic;
public class Program
{
public void Method1(string str1, int int2)
{
Console.WriteLine("Method1 invoked! " + str1 + " " + int2);
}
public void Method2(int int2)
{
Console.WriteLine("Method2 invoked! " + int2);
}
public void Method3()
{
Console.WriteLine("Method3 invoked!");
}
public static void Main()
{
var instance = new Program();
//using BindingFlags get all non-static, public methods that are declared in type Program
MethodInfo[] methods = typeof(Program).GetMethods(BindingFlags.Instance|BindingFlags.Public|BindingFlags.DeclaredOnly);
foreach (MethodInfo info in methods)
{
ParameterInfo[] parameters = info.GetParameters();
//var parms = parameters.Length > 0 ? new Object[] {"Hello ", 2} : null;
List<Object> parms = new List<Object>();
foreach (ParameterInfo param in parameters) {
Console.WriteLine(param.Name + " Type: " + param.ParameterType);
switch(param.ParameterType.ToString())
{
case "System.String" :
parms.Add("Hello");
break;
case "System.Int32" :
parms.Add(2);
break;
}
}
Console.WriteLine("Method name: "+info.Name+" : parameter.Length: "+parameters.Length);
info.Invoke(instance, parms.ToArray());
}
}
}