パラメータを使用してリフレクションを介してメソッドを呼び出そうとしていますが、次のようになります。
オブジェクトがターゲット タイプと一致しません
パラメータなしでメソッドを呼び出すと、正常に動作します。メソッドを呼び出すと、次のコードに基づいて、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);
}
}
}
}
}