212定义集 定义集合类 An ima|s WriteLine("Using custom collection class Animals: Animals animalCollection new Animalso animalCollection. Add(new Cow("Lea ) foreach (Animal myAnimal in animalcollection) IriteLine($"New myAnimal. ToString(] object added to custom collection, name=my Animal Name]") Console. ReadKey o Using custom collection class Animals: New Ch11Ex02 Cow object added to custom collection, name=Lea animalcollection[oJ FeedO 的局部变量) Animals animalcollection 无法将带的素引应用于" Animals"类型的表达式
2.1.2 定义集合 定义集合类Animals
21.3索引符 索引符是一种特殊类型的属性,添加到类中以提供类似 于数组的访问,即对项实现简单的数字索引 public class Animals CollectionBase public void Add(Animal newAnimal) List. Add (newAnimal) public void Remove(Animal newAnimal List. Remove (newAnimal) public Animal thislint animal Index] get i return (Animal)List [animalIndex]: set List [animalIndex]= value: J
2.1.3 索引符 索引符是一种特殊类型的属性,添加到类中以提供类似 于数组的访问,即对项实现简单的数字索引
21.3索引符 ■ list.List属性返回一个 System0bjet对象,为索引符 定义一个类型,使用该索引符访问某项时,就可以得到 这个类型(即强类型化)。 可以写: an i ma Col lection[0]. Feed( 而不是:( An i ma I) an i ma Col lect ion[O].Feed0;
2.1.3 索引符 Ilist.List属性返回一个System.Object对象,为索引符 定义一个类型,使用该索引符访问某项时,就可以得到 这个类型(即强类型化)。 可以写:animalCollection[0].Feed(); 而不是:(Animal)animalCollection[0].Feed();
21.3索引符 static void Main(string[] args Animals animalCollection new Animals animal Collection. Add (new Cow("Donna")) animal Collection. Add(new Chicken( Kevin)) animalcollection[o]. FeedO foreach (Animal myAnimal in animalCollection) my Animal FeedO Donna has been fed Donna has been fed Kevin has been fed
2.1.3 索引符
214创建 Cards集 ■新类 Cards是Gard对象的一个定制集合 class Cards: CollectionBase public void Add(Card newCard) List. Add(newCard) public void Remove(Card ol dCard) List. Remove oldCard) public Card this [int cardIndex] get return (Card)List [cardIndex]: j set List [cardIndex]= value:] public void CopyTo(Cards target Cards) for (int index = 0: index< this Count: index++) targetCards [index]= this[index]
2.1.4 创建Cards集合 新类Cards是Card对象的一个定制集合