Hi,
I'm looking for a way to iterate through all methods in a class and run each method with values from an array. Thanks for the help
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AlanPosted Apr 4, 2008, 5:22 AM
Here's a quick program to show how you can call every method in a class (apart from the constructor) using reflection. Notice though that this only works reliably when all the methods have the same parameter type and are being passed the same argument. This is because the Type.Getmethods() method doesn't guarantee the order in which the methods are returned. However, you could get around this by sorting the method names first:
using System;
using System.Reflection;
class Program
{
static void Main()
{
MyClass mc = new MyClass();
int[] args = new int[]{1,2,3};
Type t = typeof(MyClass);
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic
|BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodInfo[] mia = t.GetMethods(bf);
foreach(int arg in args)
{
object[] oa = new object[]{arg};
foreach(MethodInfo mi in mia)
{
if(!mi.IsConstructor)
mi.Invoke(mc, oa);
}
Console.WriteLine();
}
Console.ReadKey();
}
}
class MyClass
{
public void MyPublicMethod(int i)
{
Console.WriteLine("MyPublicMethod called with an argument of '{0}'", i);
}
private void MyPrivateMethod(int i)
{
Console.WriteLine("MyPrivateMethod called with an argument of '{0}'", i);
}
internal static void MyStaticMethod(int i)
{
Console.WriteLine("MyStaticMethod called with an argument of '{0}'", i);
}
}