【问题标题】:C#:System.Reflection.MethodInfo cause : (Object does not match target type)C#:System.Reflection.MethodInfo 原因:(对象与目标类型不匹配)
【发布时间】:2010-10-05 03:42:15
【问题描述】:

我下面有一门课,

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

我通过下面的 System.Reflection.MethodInfo 调用,但它导致 TargetException :Object 与目标类型不匹配。

 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
    }
}

所以有什么想法吗?我尝试将 foo 的参数更改为对象,例如: foo(object s) { } ,但没有帮助。

【问题讨论】:

    标签: c#


    【解决方案1】:
       Response.Write(theMethod.Invoke(this, obj));
    

    this 参数是错误的,它指的是您的 Page 类。改为传递 instance_class。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多