How can call method dynamically in c#

138 views Asked by At

I have a class , and in this class i have many method and i wanna call all method with out write name

This is my code and it work :

System.Reflection.MethodInfo[] methods = typeof(content).GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
        foreach (System.Reflection.MethodInfo m in methods)
        {
            Response.Write(typeof(content).GetMethod(m.Name).Invoke(null,null).ToString());
}

But i have one problem ,that code return just first method name

What should I do to get all of them? what's wrong ?

2

There are 2 answers

0
David L On BEST ANSWER

You need to invoke each method upon an instance. In the below example, .Invoke() is called against an instance of Content. That said, you're also making a redundant GetMethod() call. You can use the MethodInfo directly.

void Main()
{
    var content = new Content();

    System.Reflection.MethodInfo[] methods = typeof(Content).GetMethods(
        System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);

    foreach (System.Reflection.MethodInfo m in methods)
    {
        Response.Write(m.Invoke(content, null).ToString());
    }
}

public class Content
{
    public static void Test1() {}
    public static void Test2() {}
}
0
sirdank On

Are all the methods you want to execute public and static? Good. Now check to see if you are passing the correct parameters to each method you want to call.

Invoke(null, null) only works for methods accepting no parameters. If you try to call methods that require parameters using .Invoke(null, null), an exception will be thrown.

For example, if you have two methods

public static void Example1() { ... }
public static void Example2(string example) { ... }

This code will run Example1(), print it out, and then crash when it tries to pass 0 parameters to Example2() To invoke Example2() you would need .Invoke(null, new object[1])