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

后端 未结 5 1894
臣服心动
臣服心动 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: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;
    }
    

提交回复
热议问题