C#中動態調整數組大小的代碼

b5cw 9年前發布 | 867 次閱讀 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 ();
    }
}

}</pre>

 本文由用戶 b5cw 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!