我们可以创建自己的集合,可以从System.Collections.CollectionBase类中派生,CollectionBase实现了接口IEnumerable,ICollection,IList.
- public abstract class Animal//父类,抽象类
- {
- private string name;
- public string Name
- {
- set { this.name = value; }
- get { return this.name; }
- }
- public Animal() {
- this.name = "the animal no name";
- }
- public Animal(string name) {
- this.name = name;
- }
- public void Feed() => Console.WriteLine($"{name} has been fed");
- }
- //子类继承自Animal
- class Chicken:Animal
- {
- public Chicken(string name) : base(name) { }
- public void LayEgg() => Console.WriteLine($"{Name} has been Lay an Egg");
- }
- //子类继承自Animal
- class Cow:Animal
- {
- public Cow(string name) : base(name) { }
- public void Milk() => Console.WriteLine($"{Name}has been Milked");
- }
//IList CollectionBase 通过继承CollectionBase类实现自定义集合
- public class Animals : CollectionBase
- {
- public void Add(Animal ani)//添加方法
- {
- List.Add(ani);
- }
- public void Remove(Animal ani)//删除方法
- {
- List.Remove(ani);
- }
- public Animal this[int i]//索引器,和this关键字一起使用,使用索引器就可以使用Animal[0]这种方式访问。
- {
- get { return (Animal)List[i]; }
- set { List[i] = value; }
- }
- }
- //Main方法
- static void Main(string[] args){
- Animal animal = new Cow("ss");
- //定义初始化自定义集合方法
- Animals aniCollection = new Animals//
- {
- new Cow("Lea"),
- new Chicken("Deer")
- };
- //方法2,使用Add()方法添加
- aniCollection.Add(animal);
- foreach (Animal a in aniCollection)
- {
- Console.WriteLine($"New {a.ToString()}" + $" Name={a.Name}");
- }
- //Remove方法
- aniCollection.Remove(animal);
- foreach (Animal a in aniCollection)
- {
- Console.WriteLine($"New {a.ToString()}" + $" Name={a.Name}");
- }
- aniCollection[0].Feed();//使用索引器访问
- }