正确的语法以按名称调用方法

时间:2013-10-13 17:18:54

标签: c# reflection invoke

下面的代码正确地找到了类和方法,但它在method.Invoke(this, null);

上给出了以下错误
System.Reflection.TargetException was unhandled
  HResult=-2146232829
  Message=Object does not match target type.
  Source=mscorlib
  StackTrace:.....

调用void方法的正确语法是什么?

using System;
using System.Reflection;
using System.Windows;

namespace ProjectXYZ
{
    class NavigateOptions
    {


        public bool runMethod(string debug_selectedClass)
        {
            Type t = Type.GetType("ProjectXYZ." + debug_selectedClass);
            MethodInfo method = t.GetMethod("test");
            if (method.IsStatic)
                method.Invoke(null, null);
            else
                method.Invoke(this, null);

            return true;

        }
    }

    public class Option72
    {
        public void test()
        {
            string hasItRun = "Yes";
        }
    }
}

1 个答案:

答案 0 :(得分:2)

this(您调用该方法的类)不是定义test()方法的类。您必须提供该类的实例(由{指示的那个) {1}})在其上调用非静态方法。

如果它有一个空的构造函数,你可以这样做:

debug_selectedClass
相关问题