
集合的创建
对于简单的数组来说,只有用固定的大小来初始化数组,才能使用它。
Animal[] animalArray = new Aimal[2];
而ArrayList集合不需要初始化其大小
ArrayList animalArrayList = new ArrayList();
这个类还有另外两个构造函数。第一个构造函数把现有的集合作为一个参数,把现有集合的内容复制到新实例中;而另一个构造函数通过一个参数设置集合的容量(capacity)。这个容量用一个int值指定,设置集合中可以包含的初始项数。但这并不是真实的容量,因为如果集合中的项数超过了这个值,容量就会自动增加一倍。
对于ArrayList集合,它没有现成的项,也没有null引用的项。我们使用ArrayList对象的Add()方法添加新项:
Cow myCow2 = new Cow("Hayley");
anmialArrayList.Add(myCow2);
anmialArrayList.Add(new Chicken("Roy"));
ArrayList对象支持IEnumerable接口,这个接口的唯一方法GetEnuumerator()可以迭代集合中的各项。所以可以与foreach一起使用
foreach (Animal myAnimal in animalArrayList)
{
Console.WriteLine("New {0} object added to ArrayList collection,Name = {1}",myAnimal.Tostring(),myAnimal.Name);
}
ArrayList集合是System.Object对象的集合(通过多态性赋给Animal对象),所以必须用所有的项进行数据类型转换:
((Animal)animalArrayList[0]).Feed();
((Chichen)animalArrayList[1]).LayEgg();
我们可以使用Remove()和RemoveAt()方法删除项,这两个方法是在ArrayList类中实现的IList接口的一部分。它们分别根据项的引用或索引从集合中删除项:
animalArrayList.RemoveAt(0);
animalArrayList.Remove(myCow2);
ArrayList集合可以用AddRange()方法一次添加好几个项。这个方法接受带有ICollection接口的任何对象,包括数组:
animalArrayList.AddRange(animalArray);
AddRange()方法不是ArrayList提供的任何接口的一部分。这个方法专用于ArrayList类,
希望本文所述对大家C#程序设计有所帮助。
注:相关教程知识阅读请移步到c#教程频道。










