C#: Is there a way to resize an array of unknown type using reflection?

后端 未结 5 1825
臣服心动
臣服心动 2021-01-25 02:06

My users pass me an array of some type, say int[] or string[]. I can easily query the types of the elements via GetElementType, and I can find out how long the array was when i

相关标签:
5条回答
  • 2021-01-25 02:39

    In case anyone is curious, I ended up switching my code to use List

    0 讨论(0)
  • 2021-01-25 02:48

    I agree with the comments that you should be using List(Of T), but if you want to copy your array into a new array of the same type, you could do something like the following.

    // Your passed in array.
    object[] objs = new object[5] {1,2,3,4,5};
    
    // Create an array of the same type.
    Array a = Array.CreateInstance(objs[0].GetType(), objs.Length+3);
    
    // Copy in values.
    objs.CopyTo(a,0);
    
    0 讨论(0)
  • 2021-01-25 02:58

    This should work:

    static void Resize(ref Array array, int newSize) {        
        Type elementType = array.GetType().GetElementType();
        Array newArray = Array.CreateInstance(elementType, newSize);
        Array.Copy(array, newArray, Math.Min(array.Length, newArray.Length));
        array = newArray;
    }
    
    0 讨论(0)
  • 2021-01-25 02:59

    Why not just create a new array of whichever type you need that is the size that you want? Then populate it from the array you want to resize, setting non existent values to some default.

    0 讨论(0)
  • 2021-01-25 03:04

    I guess I'll just switch to using Lists, but this is a shame; the code will be quite a bit messier looking and since my users are basically at the level of first-semester ugrads, each little thing will make their lives less good. But I'm suspecting that you folks don't see a way to do this either. Oh well....

    0 讨论(0)
提交回复
热议问题