表示今天被一个问题困惑到了。C#中数组的Length的大小到底是数组申请内存大小还是实际存储的元素长度。我们可以
int[] a = new int[10];
a[0]=1;
a[1]=2;
a[2]=3; //但是我只初始化前三个元素
如果在保留数组中原有的内容的基础上,怎么设置一个Resize(int[] arr, int newsize)方法,供我们调节(增大或减小)数组长度。
这样我还能用a.Length吗?
在网上找到一个resize的代码~是用Length的~
先记着这个问题,自己下去再试试吧~
转自http://www.source-code.biz/snippets/csharp/1.htm
How to resize an array in C#
In C#, arrays cannot be resized dynamically. One approach is to use System.Collections.ArrayList instead of a native array. Another (faster) solution is to re-allocate the array with a different size and to copy the contents of the old array to the new array. The generic function resizeArray (below) can be used to do that.
// Reallocates an array with a new size, and copies the contents // of the old array to the new array. // Arguments: // oldArray the old array, to be reallocated. // newSize the new array size. // Returns A new array with the same contents. public static System.Array ResizeArray (System.Array oldArray, int newSize) { int oldSize = oldArray.Length; System.Type elementType = oldArray.GetType().GetElementType(); System.Array newArray = System.Array.CreateInstance(elementType,newSize); int preserveLength = System.Math.Min(oldSize,newSize); if (preserveLength > 0) System.Array.Copy (oldArray,newArray,preserveLength); return newArray; }
// Test routine for ResizeArray(). public static void Main () { int[] a = {1,2,3}; a = (int[])ResizeArray(a,5); a[3] = 4; a[4] = 5; for (int i=0; i<a.Length; i++) System.Console.WriteLine (a[i]); }