C#调整未知类型的数组

时间:2011-02-23 22:40:06

标签: c# arrays

  

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

您好,

有没有办法调整未知类型的数组?请参阅下面的示例代码。

object ReadArray()
{
    Type classType = Type.GetType(arrayItemName, true);
    object arr = Array.CreateInstance(classType, 0); // unknown length

    // read length from a stream
    ResizeArray(ref arr, length)
    // populate array items from stream

    // read length2 from  stream2
    ResizeArray(ref arr, length+length2)
    // populate array items from stream2

    return arr;
}

ResizeArray(ref object array, int n)
{
    Array arr = array as Array;
    Array.Resize(ref arr, n); // compile error! type can't be inferred
    array = arr;
}

3 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

除了上面链接的方法,您可以尝试使用反射;这样的事情应该有效(即使我认为它不会更好,更快,或任何事情):

static void ResizeArray(ref object array, int n)
{
    var type = array.GetType();
    var elemType = type.GetElementType();
    var resizeMethod = typeof(Array).GetMethod("Resize", BindingFlags.Static | BindingFlags.Public);
    var properResizeMethod = resizeMethod.MakeGenericMethod(elemType);
    var parameters = new object[] { array, n };
    properResizeMethod.Invoke(null, parameters);
    array = parameters[0];
}

答案 2 :(得分:-2)

Resize(ref object array, int size){
    object[] newarray = new object[size];
    for(int i=0;i<array.length&&i<size;i++){
        newarray[i] = array[i];
    }
    array = newarray;
}