为什么我不能通过字符串调用此方法?

One*_*key 2 .net c# reflection method-invocation

反思新手的问题.我在Windows窗体中有一个方法:

private void handleOrderCode()
{
  //...do stuff
}
Run Code Online (Sandbox Code Playgroud)

我试图以下列方式打电话:

Type t = this.GetType();
MethodInfo mi = t.GetMethod("handleOrderCode");
if (mi != null) mi.Invoke(this, null);
Run Code Online (Sandbox Code Playgroud)

我已经确认"这个"不是空的.字符串"handleOrderCode"已被硬编码的空间将在此工作时替换为字符串变量.但是,目前"mi"在最后一行的if语句中求值时始终为null.

那么我做错了什么?

aba*_*hev 10

您需要指定绑定标志:

using System.Reflection;

t.GetMethod("handleOrderCode", BindingFlags.Instance | BindingFlags.NonPublic)
Run Code Online (Sandbox Code Playgroud)

因为没有任何标志的过载意味着

BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance
Run Code Online (Sandbox Code Playgroud)

即不会返回任何非公开(私人,受保护等)成员.


Jon*_*eet 5

参数重载Type.GetMethod只查找公共方法:

搜索具有指定名称的公共方法.

您需要为另一个重载指定适当的BindingFlags值:

MethodInfo method = t.GetMethod("handleOrderCode",
                                BindingFlags.Instance | BindingFlags.NonPublic);
Run Code Online (Sandbox Code Playgroud)

请注意,您需要在此处(或两者)指定"实例"或"静态",而不仅仅是"非公开".如果你想要寻找公共方法,你也必须包含它.

另一种选择只是让你的方法公开:)

(另外,我建议将其重命名HandleOrderCode为更常规,惯用的C#.)