mercredi 26 juillet 2017

Why does Method Invoke fail with argument exception?

Consider this code sample from a WinForms app:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            object[] parms = new object[1];
            parms[0] = "foo";

            DoSomething(parms);
        }

        public static string DoSomething(object[] parms)
        {
            Console.WriteLine("Something good happened");
            return null;
        }
    }

It works as expected, when you click button1 it prints "Something good happened" to the console.

Now consider this code sample, which is the same except that it invokes DoSomething using reflection:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            object[] parms = new object[1];
            parms[0] = "foo";

            System.Reflection.MethodInfo mi = typeof(Form1).GetMethod("DoSomething");
            mi.Invoke(null, parms);

        }

        public static string DoSomething(object[] parms)
        {
            Console.WriteLine("Something good happened");
            return null;
        }
    }

It throws an System.ArgumentException on the line mi.Invoke(null, parms) (Object of type 'System.String' cannot be converted to type 'System.Object[]'.)

parms is clearly an object array, and DoSomething's method signature is clearly expecting an object array. So why is invoke pulling the first object out of the array and trying to pass that instead?

Or is something else going on that I'm not understanding?





Aucun commentaire:

Enregistrer un commentaire