//动态调整一维数组长度 public static Array Redim(Array origArray, int length) { //确定每个元素的类型 Type t = origArray.GetType().GetElementType(); //创建新的数组 Array newArray = Array.CreateInstance(t, length); //原数组中的数据拷贝到新数组中 Array.Copy(origArray, 0, newArray, 0, Math.Min(origArray.Length, length)); return newArray; }
//动态调整二维数组长度 public static Array Redim(Array origArray, params int[] lengths) { //确定每个元素的类型 Type t = origArray.GetType().GetElementType(); //创建新的数组 Array newArray = Array.CreateInstance(t, lengths); //原数组中的数据拷贝到新数组中 for (int i = origArray.GetLowerBound(0); i <= Math.Min(origArray.GetUpperBound(0), newArray.GetUpperBound(0)); i++) for (int j = origArray.GetLowerBound(1); j <= Math.Min(origArray.GetUpperBound(1), newArray.GetUpperBound(1)); j++) newArray.SetValue(origArray.GetValue(i, j), i, j); //在这里没有用Copy方法,如果用此方法,会把原数组中所有数据逐个拷贝到新数组中 return newArray; }
//如果在Redim方法中用Copy方法(动态调整二维数组长度) public static Array Redim(Array origArray, params int[] lengths) { int length = 1; for (int i = 0; i < lengths.Length; i++) length *= lengths; Type t = origArray.GetType().GetElementType(); Array newArray = Array.CreateInstance(t, lengths); Array.Copy(origArray, 0, newArray, 0, Math.Min(origArray.Length, length)); return newArray; }