Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#:System.Reflection.MethodInfo cause : (Object does not match target type)

Tags:

c#

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.

like image 299
Cheung Avatar asked Oct 05 '10 03:10

Cheung


1 Answers

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

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

like image 135
Hans Passant Avatar answered Sep 29 '22 21:09

Hans Passant