如何在c#中动态调用方法
How can call method dynamically in c#
我有一个 class ,在这个 class 中我有很多方法,我想调用所有没有写入名称的方法
这是我的代码并且有效:
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());
}
但我有一个问题,代码 return 只是第一个方法名称
我应该怎么做才能得到所有这些?怎么了?
您需要在一个实例上调用每个方法。在下面的示例中,针对 Content
的实例调用 .Invoke()
。也就是说,您还进行了多余的 GetMethod()
调用。你可以直接使用MethodInfo
。
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() {}
}
你要执行的方法都是public
和static
吗?好的。现在检查您是否将正确的参数传递给要调用的每个方法。
Invoke(null, null)
仅适用于不接受任何参数的方法。如果您尝试使用 .Invoke(null, null)
调用需要参数的方法,将抛出异常。
例如,如果您有两种方法
public static void Example1() { ... }
public static void Example2(string example) { ... }
此代码将 运行 Example1()
打印出来,然后在它尝试将 0 个参数传递给 Example2()
时崩溃 要调用 Example2()
你需要 .Invoke(null, new object[1])
我有一个 class ,在这个 class 中我有很多方法,我想调用所有没有写入名称的方法
这是我的代码并且有效:
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());
}
但我有一个问题,代码 return 只是第一个方法名称
我应该怎么做才能得到所有这些?怎么了?
您需要在一个实例上调用每个方法。在下面的示例中,针对 Content
的实例调用 .Invoke()
。也就是说,您还进行了多余的 GetMethod()
调用。你可以直接使用MethodInfo
。
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() {}
}
你要执行的方法都是public
和static
吗?好的。现在检查您是否将正确的参数传递给要调用的每个方法。
Invoke(null, null)
仅适用于不接受任何参数的方法。如果您尝试使用 .Invoke(null, null)
调用需要参数的方法,将抛出异常。
例如,如果您有两种方法
public static void Example1() { ... }
public static void Example2(string example) { ... }
此代码将 运行 Example1()
打印出来,然后在它尝试将 0 个参数传递给 Example2()
时崩溃 要调用 Example2()
你需要 .Invoke(null, new object[1])