This article is currently in the process of being translated into Chinese (~50% done).
类 :
More abstract classes
上一章介绍了抽象类。本章会把上一章的例子稍微扩展,增加一些抽象方法。抽象方法只能在抽象类中定义。其定义基本与常规方法一样,只是方法内部没有代码:
abstract class FourLeggedAnimal
{
public abstract string Describe();
}
那么为何要定义一个什么也不做的空方法呢?因为抽象方法表示这是抽象类的所有子类都必需要实现的方法。实际上编译时就会进行检查以确保所有的抽象方法都在子类中得以实现。这再次说明这是一种给某事物建立基类,同时还保持对子类行为一定程度的控制的好方法。基于这一点,就总是可以把子类作为一个基类对待,使用基类中作为抽象方法定义的方法。例如下面的代码:
namespace AbstractClasses
{
class Program
{
static void Main(string[] args)
{
System.Collections.ArrayList animalList = new System.Collections.ArrayList();
animalList.Add(new Dog());
animalList.Add(new Cat());
foreach(FourLeggedAnimal animal in animalList)
Console.WriteLine(animal.Describe());
Console.ReadKey();
}
}
abstract class FourLeggedAnimal
{
public abstract string Describe();
}
class Dog : FourLeggedAnimal
{
public override string Describe()
{
return "I'm a dog!";
}
}
class Cat : FourLeggedAnimal
{
public override string Describe()
{
return "I'm a cat!";
}
}
}上述代码创建了一个ArrayList来保存所有动物。然后代码分别实例化了一个新的Dog(狗)类和新的Cat(猫)类,并都加入到ArrayList中。虽然它们分别被实例化为Dog(狗)类和Cat(猫)类,但它们同时也是FourLeggedAnimal(四足动物)类,由于编译器知道此基类的所有子类都有Describe()方法,因此就可以在不知道具体动物类型的情况下调用此方法。因此,通过在foreach循环中把类型转换为FourLeggedAnimal(四足动物),仍然可以调用这些在基类中约定,实现于子类的方法。这在很多场景中非常有用。
This article has been fully translated into the following languages:
Is your preferred language not on the list? Click here to help us translate this article into your language!