C#靜態調劑數組年夜小的辦法。本站提示廣大學習愛好者:(C#靜態調劑數組年夜小的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#靜態調劑數組年夜小的辦法正文
本文實例講述了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#法式設計有所贊助。