1、集合 数据有一定的限制,最不能忍受的是一旦创建,数组的大小就固定,不能再添加。而集合则包含了数组所具有的功能,且可以任意添加/删减元素项,还有一些其他 功能。 集合的功能主要通过接口来实现,接口包含在System.Collections命名 ...
1、集合
数据有一定的限制,最不能忍受的是一旦创建,数组的大小就固定,不能再添加。而集合则包含了数组所具有的功能,且可以任意添加/删减元素项,还有一些其他 功能。
集合的功能主要通过接口来实现,接口包含在System.Collections命名空间中。
主要有:
- IEnumerable 可以迭代集合中的元素项
- ICollection(继承于IEnumerable)可以获得集合中元素项的个数,并能把元素项复制到一个简单的数组类型中。
- IList(继承于IEnumerable和ICollection)提供了集合的元素项列表,允许访问这些项,并提供其他一些与元素项列表相关的基本功能。
- IDictionary(继承于IEnumerable和ICollection)类似于IList,但提供了可通过健值访问的元素项列表。
(1)System.Array类与System.Collections.ArrayList类
1 class Program 2 { 3 static void Main(get='_blank'>string[] args) 4 { 5 Console.WriteLine("Create an Array type collection of Animal " + 6 "objects and use it:"); 7 Animal[] animalArray = new Animal[2]; 8 Cow myCow1 = new Cow("Deirdre"); 9 animalArray[0] = myCow1;10 animalArray[1] = new Chicken("Ken");11 12 foreach (Animal myAnimal in animalArray)13 {14 Console.WriteLine("New {0} object added to Array collection, " +15 "Name = {1}", myAnimal.ToString(), myAnimal.Name);16 }17 18 Console.WriteLine("Array collection contains {0} objects.", animalArray.Length);19 animalArray[0].Feed();20 ((Chicken)animalArray[1]).LayEgg();21 Console.WriteLine();22 23 Console.WriteLine("Create an ArrayList type collection of Animal " +24 "objects and use it:");25 ArrayList animalArrayList = new ArrayList();26 Cow myCow2 = new Cow("Hayley");27 animalArrayList.Add(myCow2);28 animalArrayList.Add(new Chicken("Roy"));29 30 foreach (Animal myAnimal in animalArrayList)31 {32 Console.WriteLine("New {0} object added to ArrayList collection," +33 " Name = {1}", myAnimal.ToString(), myAnimal.Name);34 }35 Console.WriteLine("ArrayList collection contains {0} objects.", animalArrayList.Count);36 ((Animal)animalArrayList[0]).Feed();37 ((Chicken)animalArrayList[1]).LayEgg();38 Console.WriteLine();39 40 Console.WriteLine("Additional manipulation of ArrayList:");41 animalArrayList.RemoveAt(0);42 ((Animal)animalArrayList[0]).Feed();43 animalArrayList.AddRange(animalArray);44 ((Chicken)animalArrayList[2]).LayEgg();45 Console.WriteLine("The animal called {0} is at index {1}.",46 myCow1.Name, animalArrayList.IndexOf(myCow1));47 myCow1.Name = "Janice";48 Console.WriteLine("The animal is now called {0}.",49 ((Animal)animalArrayList[1]).Name);50 Console.ReadKey();51 }52 }
原标题:第11章 集合、比较和转换(C#入门经典第6版)
关键词:C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。