错误:System.Reflection.TargetParameterCountException未被用户代码处理

时间:2017-08-01 14:11:39

标签: c#

代码如下:

public static class ResLocator
{
    public static string Resolve(Type assemblyObjectType, string resourceName)
    {
        MethodInfo resourceLocatorMethod = typeof(System.Web.Handlers.AssemblyResourceLoader).GetMethod(
                "GetWebResourceUrlInternal", BindingFlags.Static | BindingFlags.NonPublic, null,
                CallingConventions.Any, new[] { typeof(Assembly), typeof(string), typeof(bool), typeof(bool), typeof(ScriptManager) }, null);

        string url = string.Format("/{0}", resourceLocatorMethod.Invoke(
            null,
            new object[] { Assembly.GetAssembly(assemblyObjectType), resourceName, false })
        );

        return url;
    }
}

错误:System.Reflection.TargetParameterCountException未被用户代码处理,出现在Invoke上。

我不确定我的代码有什么问题。

1 个答案:

答案 0 :(得分:4)

在此,您需要为您要查找的方法指定参数类型:

new[] { typeof(Assembly), typeof(string), typeof(bool), typeof(bool), typeof(ScriptManager) }

在这里,您需要指定与这些参数对应的参数值:

new object[] { Assembly.GetAssembly(assemblyObjectType), resourceName, false })

所以你提供了3个参数,但有5个参数。那不行。在调用方面,例外甚至可以告诉你你做错了什么。

更重要的是,调用像这样的内部方法是非常糟糕的主意。当然,现在存在 - 但它可能很容易在库的未来版本中更改,此时您的代码即使现在正在运行也会中断。如果图书馆的作者打算让你打电话,那么他们就已公开了。

反思非常重要并且有很多有效的用途,特别是在测试自己的代码时,但 是一个好主意,可以有效地尝试在其他库中调用代码你并不打算访问。