samedi 24 octobre 2015

Difficulty re-sizing array with reflection

I'm trying to re-size an arbitrarily-typed array with reflection. Here's my code:

public static void TestResizeArray()
{
    int[]
        ints;
    Array
        arrayOfInts;

    ints = new int[ 3 ];
    arrayOfInts = (Array) ints;
    ResizeArray( ref arrayOfInts, 5 );
    Debug.Assert( arrayOfInts.Length == 5 ); // passes
    Debug.Assert( ints.Length == 5 ); // FAILS <<<<<<<<<<<
}

public static void ResizeArray(
    ref Array
        theArray,
    int
        newSize )
{
    MethodInfo
        methodInfo,
        genericMethodInfo;
    object[]
        parameters;

    methodInfo = typeof( Array ).GetMethod(
        "Resize",
        BindingFlags.Public | BindingFlags.Static );
    genericMethodInfo = methodInfo.MakeGenericMethod(
        theArray.GetType().GetElementType() );
    parameters = new object[] { theArray, newSize };
    genericMethodInfo.Invoke( null, parameters );
    theArray = (Array) parameters[ 0 ];
}

Calling the generic Array.Resize(...) function is working, in that parameters[0] contains the re-sized array, but it didn't change the theArray variable. Setting theArray to parameters[0] partially works, in that arrayOfInts in the calling function gets re-sized, but that seems to disconnect the ints array from arrayOfInts.

How can I change this so that the ints array gets resized?

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire