C#.NET不同类实现一个接口的事例

不同类实现一个接口的事例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

interface ILiveBird
{
string BabyCalled();
}
class Animal { }

class Cat: Animal, ILiveBird
{
string ILiveBird.BabyCalled()
{
return "Kitten";
}
}
class Dog:Animal, ILiveBird
{
string ILiveBird.BabyCalled()
{
return "Puppy";
}
}
class Bird: Animal
{
}

class Program
{
static void Main()
{
Animal[] animalArray = new Animal[3];
animalArray[0] = new Cat();
animalArray[1] = new Dog();
animalArray[2] = new Bird();

foreach (Animal a in animalArray) {
ILiveBird b = a as ILiveBird; // 关键代码
if (b != null) {
Console.WriteLine("昵称是:{0}", b.BabyCalled());
}
}

Console.Read();
}
}

输出:

1
2
昵称是:Kitten
昵称是:Puppy

ILiveBird b = a as ILiveBird; // 关键代码as转换,失败不会报异常,而是返回null

感谢支持!