views:

924

answers:

3

Hello,

I am trying to invoke a method via reflection with parameters and I get "object does not match target type". 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 got an exception. Is something wrong with my code?

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);
                }
            }
        }
    }
}
+5  A: 

Change "methodInfo" to "classInstance", just like in the call with the null parameter array.

  result = methodInfo.Invoke(classInstance, parametersArray);
womp
Oh my God I haven't noticed that, I am so dizzy :) Thank you
Ioannis
That's what we're here for ;)
womp
+2  A: 

A fundamental mistake is here:

result = methodInfo.Invoke(methodInfo, parametersArray); 

You are invoking the method on an instance of MethodInfo. You need to pass in an instance of the type of object that you want to invoke on.

result = methodInfo.Invoke(classInstance, parametersArray);
Jason
Yes I haven't noticed that, Thank you (was working many hours :))
Ioannis
+3  A: 

You have a bug right there

result = methodInfo.Invoke(methodInfo, parametersArray);

it should be

result = methodInfo.Invoke(classInstance, parametersArray);
Oleg I.
Yes I haven't noticed that, Thank you (was working many hours :))
Ioannis