我试图通过带参数的反射调用一个方法,我得到:
object does not match target type
如果我调用一个没有参数的方法,它工作正常。基于以下代码,如果我调用方法 Test("TestNoParameters")
,它工作正常。但是,如果我调用 Test("Run")
,则会出现异常。我的代码有问题吗?
我最初的目的是传递一个对象数组,例如public void Run(object[] options)
但这没有用,我尝试了一些更简单的方法,例如字符串没有成功。
// 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”,就像在使用空参数数组的调用中一样。
result = methodInfo.Invoke(classInstance, parametersArray);
关于c# - 反射(reflection):如何调用带参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2202381/