2017-08-01 125 views
0

的代码看起来未处理如下:错误:System.Reflection.TargetParameterCountException是由用户代码

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是由用户代码未处理的,上来就调用。

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

+2

除了你依靠内部实现细节来开始?那么这听起来像你用错误的参数调用方法。该方法在哪里申报? (如在,你有链接到源?) –

+1

可能[这一个](https://referencesource.microsoft.com/#System.Web/Handlers/AssemblyResourceLoader.cs,c3179e7329c55e12),@JonSkeet。 –

+2

那么,如果OP提供了3个参数,并且该方法有5个参数,那么这个错误就可以理解。 –

回答

4

在这里,你指定的方法的参数,你要寻找的类型:

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

在这里,你指定的参数值对应于这些参数:

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

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

更重要的是,调用这样的内部方法是真的很糟糕的主意。当然,现在已经存在 - 但在未来版本的库中很容易发生变化,此时,即使代码正在运行,代码也会中断。如果图书馆的作者打算给你打电话,他们会公开的。

反思是重要的,有很多有效的用途,特别是围绕测试自己的代码,但它不是一个好主意,用它来有效地尝试调用的代码中,你不是要访问其他库至。

+0

没问题,但我看不到另一种方式从MVC应用程序中的外部程序集访问嵌入式JavaScript文件。 – tesicg

+0

@tesicg:如果它被嵌入到程序集中,为什么不使用'Assembly.GetManifestResourceStream'? –

+0

下面是一个示例:http://coding.altervista.org/blog/2012/07/asp-net-mvc-caricare-un-file-javascript-embedded/ – tesicg

相关问题