Can Spielt
Can Spielt

Reputation: 27

Reflection call method - Argument Exception

I've a Dictionary<string, object> for my commands. All commands has a class what extends from Cmd class. Now I try to call the OnExecute method, but I get an ArgumentException.

This is my function to call the method:

public void Execute(string command, string[] args)
    {
        try {
            Type type = commands[command].GetType();
            MethodInfo method = type.GetMethod("OnExecute");
            method.Invoke(commands[command], args);
        }
        catch (ArgumentException ex)
        {
            Program.Exception(ex);
        } catch (TargetException ex)
        {
            Program.Exception(ex);
        }
    }

And this is my Cmd class

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Valda.Valda.Command
{
    public class Cmd
    {

        public Cmd()
        {

        }

        public void OnExecute(string[] args)
        {
            Program.WriteLine(args.ToString());
        }
    }
}

Upvotes: 1

Views: 463

Answers (3)

dmeglio
dmeglio

Reputation: 2830

The Invoke method takes two parameters, the Instance that has the method to invoke and an array representing the parameters. In your case, your first parameter is an array. As a result, what you're sending to the method is each member of your string array as an individual parameter rather than the array as the first parameter. What you want is:

new object[] {args}

This will make your args the first parameter to the OnExecute method.

Upvotes: 1

SlaneR
SlaneR

Reputation: 714

You have to pass parameter as object[] type.

So, you must pass parameter like this:
method.Invoke(commands[command], new object[] {args});

not like this:
method.Invoke(commands[command], args);

MethodBase.Invoke method requires an parameter as object array(object[]) so you must make an object array and store all your parameters into array.

Upvotes: 2

Alexei Levenkov
Alexei Levenkov

Reputation: 100610

Since your method takes one parameter (OnExecute(string[] args)) that is array of strings you need to pass array with single element of type string[] to Invoke method:

 method.Invoke(commands[command], new object[] {args});

Upvotes: 2

Related Questions