书第 11 章的示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics; // 调试
using System.Collections;
namespace benben_CSharp_first
{
// 定义 动物 抽象类
public class Animals : CollectionBase
{
protected string name;
public void Add(Animals newAnimal)
{
List.Add(newAnimal);
}
public void Remove(Animals newAnimal)
{
List.Remove(newAnimal);
}
public Animals this[int animalIndex]
{
get
{
return (Animals)List[animalIndex];
}
set
{
List[animalIndex] = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public Animals()
{
name = "The animal with no name.. ";
}
public Animals(string newName)
{
name = newName;
}
public void Feed()
{
Console.WriteLine("{0} has been fed.", name);
}
}
// 奶牛 类
public class Cow : Animals
{
public void milk()
{
Console.WriteLine("{0} has been milked.", name);
}
public Cow(string newName)
: base(newName)
{
}
}
// 鸡 类
public class Chicken : Animals
{
public void LayEgg()
{
Console.WriteLine("{0} has laid an egg..", name);
}
public Chicken(string newName)
: base(newName)
{
}
}
class Test
{
static void Main()
{
Animals animalCollection = new Animals();
animalCollection.Add(new Cow("Jack"));
animalCollection.Add(new Chicken("Vera"));
foreach (Animals myAnimal in animalCollection)
{
myAnimal.Feed();
}
Console.ReadKey();
}
}
}