网站logo模板成人电脑培训班附近有吗
ArrayList类与List类的用法差不多,提供的方法也差不多。但是与List不同的是,ArrayList可以包含任意类型的数据,但是相应的,要使用包含的数据,就必须对数据做相应的装箱和拆箱(关于装箱和拆箱,请参看【2.4.5】节)。
ArrayList常用属性:
- Count:返回包含的数据数量。
ArrayList常用方法:
- Add:在结尾处添加数据。
- Insert:在指定位置处插入数据。
- RemoveAt:移除指定位置的数据。
- Clear:移除所有元素。
- Contains:确定某元素是否在ArrayList中。
- IndexOf:搜索指定的Object,并返回第一个匹配项的从零开始索引。
- LastIndexOf:搜索指定的Object,并返回最后一个匹配项的从零开始索引。
【例 4.11】【项目:code4-011】 ArrayList的用法。
static void Main(string[] args)
{
ArrayList arrDate = new ArrayList();
string addString = "this is a test";
int addInteger = 123;
DateTime addDateTime = new DateTime(2025, 1, 1, 10, 10, 10);
//添加元素
arrDate.Add(addString);
arrDate.Add(addInteger);
arrDate.Add(addDateTime);
//显示数量
Console.WriteLine("包含数据数量:" + arrDate.Count);
//获得ArrayList中的元素
string toString = (string)arrDate[0];
int toInteger = (int)arrDate[1];
DateTime toDateTime = (DateTime)arrDate[2];
Console.WriteLine("数据1:{0}", toString);
Console.WriteLine("数据2:{0}", toInteger);
Console.WriteLine("数据3:{0}", toDateTime);
//查找数据是否在ArrayList中
if (arrDate.Contains(toDateTime) == true)
Console.WriteLine("包含指定的日期数据");
else
Console.WriteLine("没有指定的日期数据");
//获得数据在ArrayList中的索引位置
int pos;
pos = arrDate.IndexOf(toInteger);
if (pos > -1)
Console.WriteLine("整数数据所在索引为" + pos);
else
Console.WriteLine("没有指定的整数数据");
Console.ReadKey();
}
运行结果如下图所示:
图4-10 ArrayList的用法