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 ?
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() {}
}