12.5 实现具有相同成员的接口
因为类可以实现多个接口,有可能在两个或更多的接口中出现具有相同签名的成员。此时,可以提供一种实现,以供所有定义了该成员的接口共享,也可以显式地定义接口成员实现(详见12.6节)。
接下来,我们使用一个例子来说明。定义两个接口ISample和ISample2,它们都定义了方法Method1,两个方法的签名和返回值均相同。然后再定义一个类ClassOne,它实现了这两个接口,并在ClassOne类中提供了Method1方法的实现,如代码清单12-8所示。
代码清单12-8 实现具有相同成员的接口
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 public void Method1()//提供一个共同实现
14{
15 System.Console.WriteLine("from ClassOne.ISample.Method1()");
16}
17}
18
19 class ClassExample
20{
21 public static void Main()
22{
23 ISample sample=new ClassOne();
24 ISample2 sample2=new ClassOne();
25 sample.Method1();
26 sample2.Method1();
27}
28}
上述代码的运行结果如下:
from ClassOne.ISample.Method1()
from ClassOne.ISample.Method1()
上述代码的图示见图12-8。
图 12-8 实现具有相同成员的接口