The error: System.Reflection.TargetParameterCountException was unhandled by user code

The code looks as following:

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

The error: System.Reflection.TargetParameterCountException was unhandled by user code, comes up on Invoke.

I'm not sure what's wrong with my code.

Jon Skeet
people
quotationmark

Here, you're specifying the types of the parameters for the method you're looking for:

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

Here, you're specifying the argument values to correspond to those parameters:

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

So you've provided 3 arguments, but there are 5 parameters. That's not going to work. The exception even tells you what you're doing wrong, in terms of the invocation.

More importantly, invoking internal methods like this is a really bad idea. Sure, that exists now - but it could easily change in a future version of the library, at which point your code would break even if it were working now. If the author of the library had intended you to call it, they'd have made it public.

Reflection is important and has plenty of valid uses, particularly around testing your own code, but it's not a good idea to use it to effectively try to call code in other libraries which you're not meant to have access to.

people

See more on this question at Stackoverflow