日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#中數組擴容的幾種方式介紹_C#教程

作者:Darren?Ji ? 更新時間: 2022-10-23 編程語言

假設有一個規定長度的數組,如何擴容呢?最容易想到的是通過如下方式擴容:

    class Program
    {
        static void Main(string[] args)
        {
            int[] arrs = new[] {1, 2, 3, 4, 5};
            arrs[5] = 6;
        }
    }

報錯:未處理IndexOutOfRanageException,索引超出了數組界限。

創建一個擴容的臨時數組,然后賦值給原數組,使用循環遍歷方式

        static void Main(string[] args)
        {
            int[] arrs = new[] {1, 2, 3, 4, 5};
            int[] temp = new int[arrs.Length + 1];
            //遍歷arrs數組,把該數組的元素全部賦值給temp數組
            for (int i = 0; i < arrs.Length; i++)
            {
                temp[i] = arrs[i];
            }
            //把臨時數組賦值給原數組,這時原數組已經擴容
            arrs = temp;
            //給擴容后原數組的最后一個位置賦值
            arrs[arrs.Length - 1] = 6;
            foreach (var item in arrs)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }

創建一個擴容的臨時數組,然后賦值給原數組,使用Array的靜態方法

像這種平常的數組間的拷貝,Array類肯定為我們準備了靜態方法:Array.Copy()。

        static void Main(string[] args)
        {
            int[] arrs = new[] {1, 2, 3, 4, 5};
            int[] temp = new int[arrs.Length + 1];
            Array.Copy(arrs, temp, arrs.Length);
            //把臨時數組賦值給原數組,這時原數組已經擴容
            arrs = temp;
            //給擴容后原數組的最后一個位置賦值
            arrs[arrs.Length - 1] = 6;
            foreach (var item in arrs)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }

使用Array的靜態方法擴容

但是,拷貝來拷貝去顯得比較繁瑣,我們也可以使用Array.Resize()方法給數組擴容。

        static void Main(string[] args)
        {
            int[] arrs = new[] {1, 2, 3, 4, 5};
            Array.Resize(ref arrs, arrs.Length + 1);
            //給擴容后原數組的最后一個位置賦值
            arrs[arrs.Length - 1] = 6;
            foreach (var item in arrs)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }

總結:數組擴容優先考慮使用Array的靜態方法Resize,其次考慮把一個擴容的、臨時的數組賦值給原數組。

原文鏈接:https://www.cnblogs.com/darrenji/p/3978150.html

相關推薦

欄目分類
最近更新