samedi 14 mars 2020

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

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?





Aucun commentaire:

Enregistrer un commentaire