数组实现位System.Array类的实例,实现了IList,ICollection,IEnumerable接口,数组一旦创建大小固定,不能添加,删除元素。
- 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");
- }
- static void Main(string[] args){
- Animal[] animalArray = new Animal[2];//定义数组,长度为2
- Cow myCow1 = new Cow("Lea");
- animalArray[0] = myCow1;//给数组赋值
- animalArray[1] = new Chicken("Noa");
- foreach (Animal myAnimal in animalArray)//foreach循环输出数组内容
- {
- Console.WriteLine($"New{myAnimal.ToString()}" + $" Name={myAnimal.Name}");
- }
- Console.WriteLine(animalArray.Length);//数组的长度
- //多态
- (animalArray[0]).Feed();
- ((Chicken)animalArray[1]).LayEgg();
- }