0

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 ?

8
  • Are you sure you have more than one public static method? Commented Jun 10, 2015 at 19:55
  • Try Response.Write(m.Invoke(null,null).ToString()); Commented Jun 10, 2015 at 19:55
  • 1
    Your invoke call doesn't include the object you are calling that method on. For example, if you look at the solution here (stackoverflow.com/questions/801070/…) it calls invoke on an object which is an instance of that type: method.Invoke(instance, null);. Commented Jun 10, 2015 at 19:55
  • @Alioza yeah i'm sure , i wrote Response.Write(m.Name); returned all method name Commented Jun 10, 2015 at 20:04
  • @Oleg : i did some thing you say , but got some response again Commented Jun 10, 2015 at 20:08

2 Answers 2

2

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() {}
}
Sign up to request clarification or add additional context in comments.

Comments

1

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.