声明一个Animal类,作为之后所有继承他的动物类的基类,再声明一个ILiveBrith的接口;Cat、Dog、Bird类都继承Animal,Cat和Dog类都实现ILiverBrith接口
interface ILiveBirth
{
string BabyCalled();
}
class Animal() { }
class Cat () : Animal, ILiverBirth
{
string ILiveBirth.BabyCalled(){
return "kitten";
}
}
class Dog () : Animal, ILiverBirth
{
string ILiveBirth.BabyCalled(){
return "puppy";
}
}
class Bird () : Animal, ILiverBirth
{
}
class Program{
static void main(){
Animal [ ] animalArray = new Animal [3];
animal [0] = new Cat();
animal [1] = new Dog();
animal [2] = new Bird();
foreach (Animal a in animalArray)
{
ILiverBirth b = a as ILiverBirth; // as会在对象没有引用的时候返回一个 null
if (b != 0)
Console.WriteLine("Baby is called {0}", b.BabyCalled())
}
}
}
结果:
Baby is called kitten
Baby is called puppy
内存情况: