12.6 显式接口成员实现
如果在要实现的多个接口中,存在有相同的成员,除了12.5节所讲的“提供一个共同的实现”以外,还可以分别实现,那么怎么区别哪个方法是哪个接口的呢?答案就是采用“限定接口名称”来声明。所谓“限定接口名称”就是“接口名.方法名”的样式,类似于我们使用的“命名空间.类名”的限定方式。接下来,我们通过一个例子来学习显式接口成员的实现。首先,声明两个接口,它们都定义了Method1方法,方法的签名相同。然后定义一个类ClassOne去实现这两个接口,这里的关键就是在ClassOne类中对两个接口中的Method1方法进行分别实现,如代码清单12-9所示。
代码清单12-9 显示接口成员实现
1 interface ISample
2{
3 void Method1();
4}
5
6 interface ISample2
7{
8 void Method1();
9}
10
11 class ClassOne:ISample,ISample2
12{
13 void ISample.Method1()
14{
15 System.Console.WriteLine("from ClassOne.ISample.Method1()");
16}
17
18 void ISample2.Method1()
19{
20 System.Console.WriteLine("from ClassOne.ISample2.Method1()");
21}
22}
23
24 class ClassExample
25{
26 public static void Main()
27{
28 ClassOne clsOne=new ClassOne();
29 ISample sample1=(ISample)clsOne;
30 ISample2 sample2=(ISample2)clsOne;
31 sample1.Method1();
32 sample2.Method1();
33}
34}
上述代码的运行结果如下:
from ClassOne.ISample.Method1()
from ClassOne.ISample2.Method1()
关于代码清单12-9的说明如表12-5所示。
图12-9演示了显式接口实现的方法。
图 12-9 显式接口成员实现