自定义集合
可以通过继承System.Collections.CollectionBase 类的方式自定义集合,CollectionBase 类有接口 IEnumerable、 ICollection 和 IList,但只提供了一些简要的实现代码,特别是 IList 的 Clear()和 RemoveAt()方法,
以及 ICollection 的 Count 属性。如果要使用提供的功能,就需要自己执行其他代码。
为便于完成任务, CollectionBase 提供了两个受保护的属性,它们可以访问存储的对象本身。我们可以使用 List 和 InnerList, List 可以通过 IList 接口访问项, InnerList 则是用于存储项的 ArrayList对象。
1 public abstract class Animal 2 { 3 private string name; 4 public string Name 5 { 6 get { return name; } 7 set { name = value; } 8 } 9 10 public Animal() 11 { 12 name = "NULL"; 13 } 14 15 public Animal(string newName) 16 { 17 name = newName; 18 } 19 20 public void Feed() 21 { 22 Console.WriteLine("{0} has been fed.", name); 23 } 24 } 25 26 public class Dog:Animal 27 { 28 public void Run() 29 { 30 Console.WriteLine("Dog run...."); 31 } 32 33 public Dog(string newName) 34 : base(newName) 35 { 36 37 } 38 } 39 40 public class Bird : Animal 41 { 42 public Bird(string newName) 43 : base(newName) 44 { 45 46 } 47 48 public void Fly() 49 { 50 Console.WriteLine("Bird fly...."); 51 } 52 } 53 54 class Animals:CollectionBase 55 { 56 public void Add(Animal animal) 57 { 58 List.Add(animal); 59 } 60 61 public void Remove(Animal animal) 62 { 63 List.Remove(animal); 64 } 65 66 public Animals() 67 { 68 69 } 70 71 //通过下面代码使得Animals可以通过索引访问 72 public Animal this[int animalIndex] 73 { 74 get 75 { 76 return (Animal)List[animalIndex]; 77 } 78 set 79 { 80 List[animalIndex] = value; 81 } 82 } 83 } 84 85 static void Main(string[] args) 86 { 87 Animals animals = new Animals(); 88 animals.Add(new Dog("Jack")); 89 animals.Add(new Bird("Jason")); 90 91 foreach (Animal animal in animals) 92 { 93 animal.Feed(); 94 } 95 96 Console.WriteLine("\n\n\nPress any key to exit!"); 97 Console.ReadKey(); 98 } |
运行结果:
Jack has been fed.
Jason has been fed.
Press any key to exot!
其中, Add()和 Remove()方法实现为强类型化的方法,使用 IList 接口中用于访问项的标准 Add()方法。该方法现在只用于处理 Animal 类或派生于 Animal 的类,而前面介绍的 ArrayList 实现代码可处理任何对象。
索引符(indexer)是一种特殊类型的属性,可以把它添加到一个类中,以提供类似于数组的访问。this 关键字与方括号中的参数一起使用,但这看起来类似于其他属性。这个语法是合理的,因为在访问索引符时,将使用对象名,后跟放在方括号中的索引参数(例如 MyAnimals[0])。