1. 创建 ArrayList: 若要使用 ArrayList,首先需要在代码中实例化它。你可以使用 new 关键字创建一个新的 ArrayList 对象。
using System.Collections;
// ...
ArrayList myArrayList = new ArrayList();
2. 添加元素: ArrayList 允许你在运行时动态添加元素,可以是任何对象类型。
myArrayList.Add("Item 1");
myArrayList.Add(42);
myArrayList.Add(new CustomObject());
3. 访问元素: 通过索引访问 ArrayList 中的元素。索引从零开始。
object item = myArrayList[0];
4. 删除元素: 你可以使用 Remove 方法从 ArrayList 中删除指定的元素。
myArrayList.Remove("Item 1");
5. 遍历元素: 使用循环语句遍历 ArrayList 中的所有元素。
foreach (object item in myArrayList)
{
// 处理每个元素的逻辑
}
6. Count 属性: ArrayList 提供 Count 属性,用于获取集合中元素的数量。
int numberOfItems = myArrayList.Count;
7. 排序和反转: ArrayList 提供 Sort 方法来对元素进行排序,以及 Reverse 方法来反转元素的顺序。
myArrayList.Sort();
myArrayList.Reverse();
请注意,ArrayList 是一种非类型安全的集合,因为它可以包含任何类型的对象。在现代 ASP.NET 应用程序中,通常推荐使用泛型集合(例如 List<T>)来替代 ArrayList,因为泛型集合提供了更好的类型安全性和性能。
List<string> stringList = new List<string>();
stringList.Add("Item 1");
如果你的项目使用较新版本的 .NET,建议使用泛型集合以获得更好的类型检查和性能。
转载请注明出处:http://www.pingtaimeng.com/article/detail/6579/ASP.NET