输出的结果为:未添加前al的元素个数为:0
调用Add方法后al的元素个数为:3
调用AddRange方法后al的元素个数为:5
abc xyz opq def ghj(每一行输出一个)
二、ArrayList元素的删除
ArrayList提供了四种方法用于从ArrayList中删除元素。这四种方法是Remove,RemoveAt,RemoveRange方法和Clear方法。
Remove方法接受一个object类型值的参数,用于移除指定元素值的第一个匹配集合元素。其格式为:ArrayList 对象.Remove(值)
RemoveAt方法接受一个int类型的参数,用于删除指定索引的集合元素。其格式为:ArrayList 对象.RemoveAt(索引)
RemoveRange方法从集合中移除一定范围的元素。其格式为: ArrayList 对象.RemoveRange(开始索引,要删除的个数)
Clear方法清除所有的元素。
例二、用上述的方法实现对元素的删除
- <span style="font-size:18px;">using System; using System.Collections;//需要添加的命名空间
- using System.Collections.Generic; using System.Linq;
- using System.Text; using System.Threading.Tasks;
- namespace 动态数组的使用
- { class Program
- { static void Main(string[] args)
- { ArrayList al = new ArrayList(3);//定义的一个动态数组且初始数组元素个数为3个
- al.Add("abc"); al.Add(50);
- al.Add(10); string[] last = { "def", "ghj" };
- al.AddRange(last); Console.WriteLine("未删除前al的元素个数为:" + al.Count);
- al.RemoveAt(2);//删除索引为2后的元素 Console.WriteLine("删除索引为2后的元素个数为:"+al.Count);
- al.Remove("abc");//删除第一个值为abc的项 Console.WriteLine("删除值为abc后的元素个数为:"+al.Count);
- al.RemoveRange(1,2);//删除自索引为1的两个元素 Console.WriteLine("删除自索引为1的两个元素后的元素个数:"+al.Count);
- foreach (string item in al)//因为此对象中的元素类型不一致所以为object类型 {
- Console.WriteLine(item); }










