我试图通过带有参数的反射来调用方法,我得到:
对象与目标类型不匹配
如果我调用一个不带参数的方法,它工作得很好。如果我调用该方法,则基于以下代码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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)