using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace _1207_數組刪除元素 { class Program { //只能在動態數組ArrayList類中對數組執行刪除元素的操作。 //因為動態數組是一個可以改變數組長度和元素個數的數據類型。 //為Program類定義一個靜態方法Show public static void Show(ArrayList alist) { for (int i = 0; i < alist.Count; i++) { Console.Write("[{0}]:{1} ", i, alist[i]); } Console.WriteLine("\n"); } static void Main(string[] args) { // C#數組刪除元素 ArrayList arraylist = new ArrayList(); for (int i = 0; i < 7; i++) { arraylist.Add(i); } Console.WriteLine("1. 數組列表的容量為{0},實際包含{1}個元素:", arraylist.Capacity, arraylist.Count); Show(arraylist); arraylist.Remove(3); // 刪除數組元素 arraylist.RemoveAt(5); // 刪除指定索引位置5的元素 Console.WriteLine("2. 數組列表的容量為{0},實際包含{1}個元素:", arraylist.Capacity, arraylist.Count); Show(arraylist); Console.ReadLine(); } } }
附: 聲明數組的方法:
//定義數組
數據類型[] 數組名;
//初始化數組中的元素
數據類型[] 數組名 = new 數據類型[長度];
數據類型[] 數組名 = {值 1, 值 2, ...}
數據類型[] 數組名 = new 數據類型[長度]{值 1,值 2,...}
//定義 int 類型的數組 int[] a = {1,2,3}; //輸岀數組中的一個元素 Console.WriteLine(a[0]); //輸出數組中的最后一個元素 Console.WriteLine(a[a.Length-1]);