如何在 C# 中動態建立陣列?


動態陣列是可變長的陣列且優於靜態陣列。這是因為陣列的大小是固定的。

若要動態地在 C# 中建立陣列,請使用 ArrayList 集合。它表示可以逐個索引的物件的有序集合。它還允許動態記憶體分配、新增、搜尋和對列表中的項進行排序。

下面是一個示例,演示如何動態地在 C# 中建立陣列。

示例

 線上演示

using System;
using System.Collections;
namespace CollectionApplication {
   class Program {
      static void Main(string[] args) {
         ArrayList al = new ArrayList();
         al.Add(99);
         al.Add(47);
         al.Add(64);
         Console.WriteLine("Count: {0}", al.Count);
         Console.Write("List: ");
         foreach (int i in al) {
            Console.Write(i + " ");
         }
         Console.WriteLine();
         Console.ReadKey();
      }
   }
}

輸出

Count: 3
List: 99 47 64

更新於: 2020 年 6 月 23 日

5K+ 次瀏覽

職業起步

透過完成課程獲得認證

開始
廣告