Note that there are some explanatory texts on larger screens.

plurals
  1. POReflection: How to Invoke Method with parameters
    primarykey
    data
    text
    <p>I am trying to invoke a method via reflection with parameters and I get:</p> <blockquote> <p>object does not match target type</p> </blockquote> <p>If I invoke a method without parameters, it works fine. Based on the following code if I call the method <code>Test("TestNoParameters")</code>, it works fine. However if I call <code>Test("Run")</code>, I get an exception. Is something wrong with my code?</p> <p>My initial purpose was to pass an array of objects e.g. <code>public void Run(object[] options)</code> but this did not work and I tried something simpler e.g. string without success.</p> <pre><code>// Assembly1.dll namespace TestAssembly { public class Main { public void Run(string parameters) { // Do something... } public void TestNoParameters() { // Do something... } } } // Executing Assembly.exe public class TestReflection { public void Test(string methodName) { Assembly assembly = Assembly.LoadFile("...Assembly1.dll"); Type type = assembly.GetType("TestAssembly.Main"); if (type != null) { MethodInfo methodInfo = type.GetMethod(methodName); if (methodInfo != null) { object result = null; ParameterInfo[] parameters = methodInfo.GetParameters(); object classInstance = Activator.CreateInstance(type, null); if (parameters.Length == 0) { // This works fine result = methodInfo.Invoke(classInstance, null); } else { object[] parametersArray = new object[] { "Hello" }; // The invoke does NOT work; // it throws "Object does not match target type" result = methodInfo.Invoke(methodInfo, parametersArray); } } } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload