samedi 14 mars 2020

ArgumentException on method invocation with reflection: Object of type 'System.Object[]' cannot be converted to type 'T[]'

I'm trying to call a method with reflection. This is the class:

public class MyData<T> where T : struct
{
    public void CopyFrom(T[] array)
    { /* code */ }
}

Now I have an array that contains the objects that I want to put into the class, but my objects are boxed.

var container = new MyData<int>();
var method = typeof(MyData<>).GetMethod("CopyFrom");
object[] boxed = new object[] {1, 2, 3};
method.Invoke(container, new object[] { boxed });

The error that I get is this: System.ArgumentException: Object of type 'System.Object[]' cannot be converted to type 'T[]'.

What is the right way to call this method?

Note that this is not a generic method. So it's not duplicate of How do I use reflection to call a generic method?





Aucun commentaire:

Enregistrer un commentaire