在C#中,ArrayList和List
类型安全:
ArrayList:ArrayList是泛型集合类,它允许存储任何类型的数据。然而,由于它不是强类型的,因此在操作数据时可能会出现类型错误。
List
ArrayList:ArrayList的性能通常比List
ArrayList:ArrayList提供的方法比List
using System;
using System.Collections.Generic;
namespace ArrayListDemo
{
class Program
{
static void Main(string[] args)
{
// 创建一个ArrayList
ArrayList myArrayList = new ArrayList();
// 向ArrayList添加元素
myArrayList.Add("Apple");
myArrayList.Add("Banana");
myArrayList.Add("Cherry");
// 输出ArrayList中的元素数量
Console.WriteLine("ArrayList中的元素数量:" + myArrayList.Count);
// 遍历ArrayList并输出其中的元素
foreach (var item in myArrayList)
{
Console.WriteLine(item);
}
// 在ArrayList中查找元素并输出其索引位置
int index = myArrayList.IndexOf("Banana");
Console.WriteLine("Banana在ArrayList中的索引位置:" + index);
// 在ArrayList中移除元素并输出新元素数量
myArrayList.Remove("Cherry");
Console.WriteLine("移除元素后的ArrayList中的元素数量:" + myArrayList.Count);
// 清空ArrayList中的所有元素
myArrayList.Clear();
Console.WriteLine("清空后的ArrayList中的元素数量:" + myArrayList.Count);
Console.ReadLine();
}
}
}