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

时间:2011-04-18 11:15:52

标签: c# .net reflection method-invocation

来自Reflection新手的问题。我在Windows窗体中有一个方法:

private void handleOrderCode()
{
  //...do stuff
}

我试图以下列方式致电:

Type t = this.GetType();
MethodInfo mi = t.GetMethod("handleOrderCode");
if (mi != null) mi.Invoke(this, null);

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

那么我做错了什么?

3 个答案:

答案 0 :(得分:10)

您需要指定绑定标志:

using System.Reflection;

t.GetMethod("handleOrderCode", BindingFlags.Instance | BindingFlags.NonPublic)

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

BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance

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

答案 1 :(得分:5)

parameterless overload of Type.GetMethod仅查找公共方法:

  

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

您需要为BindingFlags指定适当的another overload值:

MethodInfo method = t.GetMethod("handleOrderCode",
                                BindingFlags.Instance | BindingFlags.NonPublic);

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

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

(另外,我建议将其重命名为HandleOrderCode,以更加传统,惯用C#。)

答案 2 :(得分:4)

尝试:

Type t = this.GetType();
MethodInfo mi = t.GetMethod("handleOrderCode", 
   BindingFlags.NonPublic | BindingFlags.Instance);
if (mi != null) mi.Invoke(this, null);
相关问题