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

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

提交回复
热议问题