Parametreleri ile yansıma yoluyla bir yöntemi çağırmaya çalışıyorum ve elde:
nesne hedef türüyle eşleşmiyor
Parametresiz bir yöntem çağırırsam iyi çalışır. Yöntemi çağırırsanız aşağıdaki kod dayanarak Test("TestNoParameters"), iyi çalışıyor. Ancak Test("Run")ararsam bir istisna alırım. Kodumda bir sorun mu var?
Benim ilk amacım nesnelerin bir dizi geçmek oldu public void Run(object[] options)ama bu işe yaramadı ve daha basit bir şey denedim, örneğin dize başarı olmadan.
// 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);
}
}
}
}
}