C #: System.Reflection.MethodInfo calls: (object does not match target type)

I have a class below

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

And I call through System.Reflection.MethodInfo below, but throws TargetException: Object does not match the type of target.

  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 will try to change the foo parameter to an object like: foo (object s) {}, but that will not help.

+6
c #
source share
1 answer
  Response.Write(theMethod.Invoke(this, obj)); 

This argument is not valid; it belongs to the class of your page. Instead, run an instance of instance_class.

+17
source share

All Articles