C#ArrayList

发布于:2025-05-01 ⋅ 阅读:(20) ⋅ 点赞:(0)

概述

ArrayList 是System.Collection.Generic 命名空间中的非泛型动态数组,它允许存储任意类型的对象(所有元素视为 object ),但缺乏类型安全性

using System.Collections;
ArrayList list = new(); // 初始化一个ArrayList

核心特性

动态扩容

  • 自动扩容:当元素数量超过当前容量时,自动分配更大的内存空间
  • 容量管理:通过Capacity 属性手动调整容量以减少扩容开销
list.Capacity = 100; // 预分配容量

混合类型存储

  • 可存储任何类型的对象(值类型会被装箱为 object
arrayList.Add(42);       // 添加整数(装箱)
arrayList.Add("hello");  // 添加字符串
arrayList.Add(new DateTime(2023, 1, 1)); // 添加日期对象

常用方法与操作

添加元素

list.Add(value);        // 末尾添加单个元素
list.Insert(index, value); // 在指定位置插入元素
list.AddRange(collection); // 批量添加(数组或其他集合)

删除元素

list.Remove(value);     // 删除第一个匹配项(返回是否成功)
list.RemoveAt(index);   // 删除指定索引的元素
list.RemoveRange(startIndex, count); // 删除一段元素
list.Clear();           // 清空所有元素

查找与遍历

bool exists = list.Contains(value); // 是否包含某元素
int index = list.IndexOf(value);    // 查找元素首次出现的索引
int lastIndex = list.LastIndexOf(value); // 查找最后一次出现的索引

// 遍历元素(需强制类型转换)
foreach (object item in list) {
    if (item is int number) {
        Console.WriteLine($"整数: {number}");
    } else if (item is string text) {
        Console.WriteLine($"字符串: {text}");
    }
}

排序与反转

list.Sort();      // 默认排序(要求元素实现IComparable)
list.Reverse();   // 反转列表顺序

// 自定义排序(需传递IComparer对象)
list.Sort(new CaseInsensitiveComparer()); // 按字符串不区分大小写排序

进阶用法

过滤特定类型

ArrayList mixedList = new ArrayList { 1, "two", 3, "four" };
List<int> numbers = mixedList.OfType<int>().ToList(); // 结果: [1, 3]

性能问题

装箱与拆箱

  • 存储值类型时:值类型会被装箱为 object ,导致内存分配和性能损失
  • 存储引用类型时:无装箱操作,但读取时仍需类型转换

类型不安全

编译时无法检测类型错误,可能导致运行时异常

ArrayList list = new ArrayList { 1, "two", 3.0 };
int first = (int)list[0];   // 正常
int second = (int)list[1];  // 运行时抛出 InvalidCastException


网站公告

今日签到

点亮在社区的每一天
去签到