//Cow的子类,有一个自己的方法Fly
class SuperCow : Cow
{
public SuperCow(string name) : base(name)
{
}
public void Fly()
{
Console.WriteLine("{0} is flying!", name);
}
public override void MakeANoise()
{
Console.WriteLine("{0} says 'I am supercow!'", name);
}
}
类准备好了之后,我们可以开始定义我们的泛型了:
复制代码 代码如下:
//继承了迭代器接口,这样方便使用Foreach 约束它的类型为Animal及其子类
public class Farm<T>:IEnumerable<T> where T : Animal
{
private List<T> animals = new List<T>();
public List<T> Animals
{
get
{
return animals;
}
}
//迭代器
public IEnumerator<T> GetEnumerator()
{
return animals.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return animals.GetEnumerator();
}
//执行所有animal的MakeANoise()
public void MakeNoises()
{
foreach (T animal in animals)
{
animal.MakeANoise();
}
}
//执行所有animal的Feed()
public void FeedTheAnimals()
{
foreach (T animal in animals)
{
animal.Feed();
}
}
//获得animals中的cow
public Farm<Cow> GetCows()
{
Farm<Cow> cowFarm = new Farm<Cow>();
foreach (T animal in animals)
{
if (animal is Cow)
{
cowFarm.Animals.Add(animal as Cow);
}
}
return cowFarm;
}
}
泛型定义好了,我们用写代码来调用它:
复制代码 代码如下: