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

注意:每个接口的实现都采用的是显式实现,所以,只有ILiveBird b = a as ILiveBird;强制转化成接口引用才能够访问实现成员;通过继承接口的类实例不能够直接访问接口的实现成员。例如,上面以animalArray[0].BayCalled()这样的形式是不能够直接访问的,必须先强制转化成接口引用类型,通过接口去访问BabyCalled()

感谢支持!