首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# ArrayList 動態陣列核心方法全解析

     編輯:關於C#

ArrayList 是 .NET Framework 早期非泛型動態陣列實現,雖然現代開發推薦使用 List<T>,但理解其核心方法對維護舊代碼、掌握集合底層原理仍有價值。本文系統梳理 ArrayList 的枚舉遍歷、常用實例方法、與 Array 的差異比較。

一、枚舉器遍歷

using System.Collections;

ArrayList list = new ArrayList(1);
for (int i = 0; i < 10; i++) list.Add(i);

IEnumerator etr = list.GetEnumerator();
while (etr.MoveNext())
    Console.Write(etr.Current + " "); // 輸出: 0 1 2 3 4 5 6 7 8 9

IEnumerator 是統一遍歷介面,foreach 底層即透過此模式實現。

二、核心實例方法實戰

ArrayList shuzu = new ArrayList(5);
shuzu.Add("仙劍一"); shuzu.Add("亮劍");
shuzu.Add("bianceng."); shuzu.Add("國家寶藏");
shuzu.Add("陸小鳳");

Console.WriteLine("原始順序:");
foreach (var item in shuzu) Console.WriteLine(item);

shuzu.Reverse(); // 反轉
Console.WriteLine("\n反轉後:");
foreach (var item in shuzu) Console.WriteLine(item);

增刪改查綜合範例

Console.WriteLine($"\n元素數: {shuzu.Count}"); // 5
shuzu.Add("new element");          // 尾端新增
Console.WriteLine($"新增後: {shuzu.Count}"); // 6

shuzu.Remove("亮劍");              // 移除首個匹配值
Console.WriteLine($"移除值後: {shuzu.Count}"); // 5

shuzu.RemoveAt(2);                 // 移除指定索引
Console.WriteLine($"移除索引後: {shuzu.Count}"); // 4

shuzu.Insert(1, "系統級");         // 指定索引插入
Console.WriteLine($"插入後: {shuzu.Count}"); // 5

int idx = shuzu.IndexOf("系統級"); // 搜尋索引 (1)
bool exists = shuzu.Contains("國家寶藏"); // true
int lastIdx = shuzu.LastIndexOf("國家寶藏");

複製與轉換

// 複製到字串陣列
string[] arr1 = new string[shuzu.Count];
shuzu.CopyTo(arr1, 0);

// 轉為物件陣列
object[] arr2 = shuzu.ToArray();

foreach (string s in arr2) Console.Write(s + " ");
foreach (string s in arr1) Console.Write(s + " ");

三、Array vs ArrayList 深度比較

特性ArrayArrayList
維度支援多維僅一維
下限可自訂固定 0
類型安全強型別(特定類型)Object 型別,須裝箱/拆箱
效能值型別優參考型別相近,值型別較差
命名空間SystemSystem.Collections
動態調整固定大小自動擴容
豐富方法靜態方法為主實例方法豐富

四、現代替代方案建議

  • 首選:List<T> — 強型別、無裝箱、效能最佳
  • 併發場景:ConcurrentBag<T>、ConcurrentQueue<T>
  • 不可變集合:ImmutableList<T>
  • 僅 .NET Framework 1.x/2.x 維護專案 才需直接使用 ArrayList

理解 ArrayList 設計權衡,有助於在遷移舊代碼或面試中展現對集合框架演進的深度認知。

Reverse 反轉示範 增刪改查綜合輸出1 增刪改查綜合輸出2
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved