6

I have a class below ,

namespace PocketWeb.AppClass
{
    public class ApiBase
    {
        public string foo(string s)
        {
            return s;
        }
    }
 }

And i call via System.Reflection.MethodInfo below, but it cause TargetException :Object does not match target type.

 protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        var instance_class = Activator.CreateInstance(Type.GetType("PocketWeb.AppClass.ApiBase"));
        Type instance_method = instance_class.GetType();
        System.Reflection.MethodInfo theMethod = instance_method.GetMethod("foo");
        object[] obj = new object[] { "hello" };
        Response.Write(theMethod.Invoke(this, obj)); //<---Error
    }
}

So any idea? i have try change the foo's parameter to object like : foo(object s) { } ,but it not help.

Cheung
  • 15,293
  • 19
  • 63
  • 93

1 Answers1

17
   Response.Write(theMethod.Invoke(this, obj));

The this argument is wrong, it refers to your Page class. Pass instance_class instead.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536