Use reflection to call methods with parameters
Problem description:
I encountered the exception "Object does not match target type" when trying to call a method with parameters via reflection. However, if the method is called without parameters, it executes successfully.
Solution:
To resolve this issue, make sure you are using the correct instance when calling the method. In the following lines in the "else" block, replace "methodInfo" with "classInstance":
<code class="language-csharp">result = methodInfo.Invoke(classInstance, parametersArray);</code>
Detailed explanation:
In object-oriented programming, each method is associated with an object instance. When calling a method through reflection, it is important to provide the correct instance to perform the call. In the provided code, the "Run" method is defined as an instance method of the "Main" class. Therefore, it must be called on an instance of the class.
Initially, try to call the method using "methodInfo" as the first parameter of the "Invoke" method. However, "methodInfo" represents a MethodInfo object, not an instance of the "Main" class. The "classInstance" variable (previously created using "Activator.CreateInstance") holds the instance that should be used for the call.
By modifying the code to call the method with "classInstance" as the first parameter, the correct instance is provided and the method can be successfully called with the specified parameters.
Modified code:
<code class="language-csharp">... if (parameters.Length == 0) { // 这部分工作正常 result = methodInfo.Invoke(classInstance, null); } else { object[] parametersArray = new object[] { "Hello" }; // 现在调用可以正常工作了 result = methodInfo.Invoke(classInstance, parametersArray); } ...</code>
The above is the detailed content of Why Does My Reflection Code Throw 'object does not match target type' When Invoking Parameterized Methods?. For more information, please follow other related articles on the PHP Chinese website!