本文實例講述了C#動態調整數組大小的方法。分享給大家供大家參考。具體如下:
通常,我們創建一個數組后就不能調整其長度,但是Array類提供了一個靜態方法CreateInstance用來創建一個動態數組,所以我們可以通過它來動態調整數組的長度。
namespace ArrayManipulation{ Class Program { static void Main (String[] args) { int[] arr = new int[]{1,2,3}; PrintArr(arr); arr = (int[])Redim(arr,5); PrintArr (arr); arr = (int[]) Redim (arr, 2); PrintArr (arr); ) public static Array Redim (Array origArray, int desiredSize) { //determine the type of element Type t = origArray.GetType().GetElementType(); //create a number of elements with a new array of expectations //new array type must match the type of the original array Array newArray = Array.CreateInstance (t, desiredSize); //copy the original elements of the array to the new array Array.Copy (origArray, 0, newArray, 0, Math.Min (origArray.Length, desiredSize)); //return new array return newArray; } //print array public static void PrintArr (int[] arr) { foreach (int x in arr) { Console.Write (x + ","); } Console.WriteLine (); } }}
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答