方法信息返回null,不确定原因

时间:2012-04-01 02:58:09

标签: c# reflection methodinfo

sealed public class HMethod
{
    public int Calc(string Method, int X1, int X2, int Y1, int Y2)
    {
        MethodInfo HMethodInfo = this.GetType().GetMethod(Method);
        return (int)HMethodInfo.Invoke(
            this, 
            new object[4] { X1, X2, Y1, Y2 }
            );
    }
    int ManhattanH(int X1, int X2, int Y1, int Y2)
    {
        //Blah
    }
    int LineH(int X1, int X2, int Y1, int Y2)
    {
        //Blah
    }
    //Other Heuristics
}

调用new HMethod().Calc("ManhattanH". X1, X2, Y1, Y2)时HMethodInfo为null。创建一个空引用Exception。它应该调用通过文本传递的方法(从文本文件中获取)

已解决:方法是私有的。

3 个答案:

答案 0 :(得分:12)

ManhattanH是私人方法。使此方法公开或使用BindingFlags.NonPublic。

答案 1 :(得分:1)

GetMethod会自动搜索该类型的公共成员。你可以通过替换这一行来解决这个问题(并让搜索包括私人成员):

MethodInfo HMethodInfo = this.GetType().GetMethod(Method, BindingFlags.Instance | BindingFlags.NonPublic);

答案 2 :(得分:0)

Type.GetMethod Method (String, Type[])

  

搜索名称区分大小写。搜索包括公共静态和公共实例方法。

     

查找构造函数和方法时,不能省略参数。   您只能在调用时省略参数。

将您的方法更改为公开并尝试此操作:

MethodInfo HMethodInfo = this.GetType().GetMethod(Method,
    new Type[]{typeof(int), typeof(int), typeof(int), typeof(int)});
相关问题