Home > Backend Development > C++ > Why Does My Reflection Code Throw 'object does not match target type' When Invoking Parameterized Methods?

Why Does My Reflection Code Throw 'object does not match target type' When Invoking Parameterized Methods?

DDD
Release: 2025-01-18 02:46:13
Original
295 people have browsed it

Why Reflection Code Throws "object does not match target type"

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template