反思:如何使用参数调用方法 [英] Reflection: How to Invoke Method with parameters
问题描述
我试图通过带参数的反射调用一个方法,我得到:
I am trying to invoke a method via reflection with parameters and I get:
对象与目标类型不匹配
如果我调用一个没有参数的方法,它工作正常.如果我调用方法 Test("TestNoParameters")
,基于以下代码,它工作正常.但是,如果我调用 Test("Run")
,则会出现异常.我的代码有问题吗?
If I invoke a method without parameters, it works fine. Based on the following code if I call the method Test("TestNoParameters")
, it works fine. However if I call Test("Run")
, I get an exception. Is something wrong with my code?
我最初的目的是传递一个对象数组,例如public void Run(object[] options)
但这不起作用,我尝试了一些更简单的方法,例如字符串没有成功.
My initial purpose was to pass an array of objects e.g. public void Run(object[] options)
but this did not work and I tried something simpler e.g. string without success.
// 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);
}
}
}
}
}
推荐答案
把methodInfo"改成classInstance",就像用空参数数组调用一样.
Change "methodInfo" to "classInstance", just like in the call with the null parameter array.
result = methodInfo.Invoke(classInstance, parametersArray);
这篇关于反思:如何使用参数调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!